Spring REST Controller Test with spring-test-mvc framework - spring

This question is next to the question I had asked here. I am using spring-test-mvc framework to test REST controller. Please see the above link to see my code for the REST Controller I have.
My test for GET is working fine but I can't do a POST. I get an exception when I try do so. This is my first time testing a REST controller.
Here's my PcUserControllerTest class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:/applicationContextTest.xml")
public class PcUserControllerTest {
#Autowired
PcUserService pcUserService;
#Autowired
PcUserController pcUserController;
PcUser pcUser;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
mockMvc = standaloneSetup(pcUserController).build();
pcUser = new PcUser("John", "Li", "Weasley", "john", "john");
pcUserService.create(pcUser);
}
#After
public void tearDown() throws Exception {
pcUserService.delete(pcUser.getId());
}
#Test
public void shouldGetPcUser() throws Exception {
this.mockMvc.perform(get("/pcusers/" + pcUser.getId()).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
#Test
public void shouldCreatePcUser() throws Exception {
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
this.mockMvc.perform(post("/pcusers/create/" + newUser).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
}
Exception I get when I execute shouldCreatePcUser:
java.lang.IllegalArgumentException: Not enough variable values available to expand ["firstName"]
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:1011)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:443)
at org.springframework.web.util.UriComponents.access$1(UriComponents.java:431)
at org.springframework.web.util.UriComponents$FullPathComponent.expand(UriComponents.java:790)
at org.springframework.web.util.UriComponents.expandInternal(UriComponents.java:413)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:404)
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:121)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.expandUrl(MockMvcRequestBuilders.java:51)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.request(MockMvcRequestBuilders.java:45)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.post(MockMvcRequestBuilders.java:28)
at com.project.cleaner.controller.test.PcUserControllerTest.shouldCreatePcUser(PcUserControllerTest.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
My PcUser looks like
#Document
public class PcUser extends BaseEntity {
private String firstName;
private String middleName;
private String lastName;
private String username;
private String password;
public PcUser() {
super();
}
public PcUser(String firstName, String middleName, String lastName,
String username, String password) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.username = username;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
// JSONObject jsonPcUser = new JSONObject();
// jsonPcUser.put("id", this.getId());
// jsonPcUser.put("firstName", this.firstName);
// jsonPcUser.put("middleName", this.middleName);
// jsonPcUser.put("lastName", this.lastName);
// jsonPcUser.put("username", this.username);
//
// return jsonPcUser.toJSONString();
return "{\"firstName\":" + this.firstName + ", "
+ "\"middleName\":" + this.middleName + ", "
+ "\"lastName\":" + this.lastName + ", "
+ "\"username\":" + this.username
+ "}";
}
}
BaseEntity:
public class BaseEntity {
#Id
private String id;
public BaseEntity() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I don't understand this exception. If anyone could guide me in the right direction would be really appreciated.

It seems, as beerbajay mentions, that the problem is that what you are trying to post to your controller is a PcUser as a URL/path parameter instead of in the actual body of the HTTP request.
I am using the org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#content(String) method to set the body of the HTTP request itself (as opposed to substitute parts of the URL or add URL parameters) like this:
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
this.mockMvc.perform(post("/pcusers/create/")
.content(newUser.toString()) // <-- sets the request content !
.accept(MediaType.APPLICATION_JSON)
.andExpect(status().isOk());

Okay, you have this as your get:
get("/pcusers/" + pcUser.getId())
Which makes sense, because you want to get the resource at /pcusers/123/, but then you have:
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
post("/pcusers/create/" + newUser)
Which doesn't really make sense since you'll be performing a toString() on the newUser object, then concatenating that with the /pcusers/create/ string. So you're probably doing a request to something like /pcusers/create/com.mycompany.PcUser#1596138, which is probably not what you want.

Related

JpaRepository findById method returning Optional.empty when id is matching to the correct database row?

For some reason my PluginRepository interface doesn't want to return the object saved in my database in this test here.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PluginServiceIntegrationTest {
#Autowired
private PluginRepository pluginRepository;
#Autowired
private PluginService pluginService;
#Autowired
private PluginController pluginController;
#LocalServerPort
private int port;
private String resourceUrl;
#Before
public void setUp() {
resourceUrl = "http://localhost:" + port + "/plugin/";
}
#Test
public void notNullTest() {
assertNotNull(pluginRepository);
assertNotNull(pluginService);
assertNotNull(pluginController);
}
#Test
public void postPluginTest() {
RestTemplate restTemplate = new RestTemplate();
PluginDTO requestDto = new PluginDTO();
HttpEntity<PluginDTO> request = new HttpEntity<>(requestDto);
ResponseEntity<PluginDTO> response = restTemplate.exchange(resourceUrl + "create", HttpMethod.POST, request, PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
PluginDTO pluginDTO = response.getBody();
assertNotNull(pluginDTO);
}
#Test
public void getPluginTest() throws Exception {
PluginDTO createdDto = new PluginDTO(UUID.fromString("20a246e8-7b74-4081-bb62-6911b8ef43ef"),"Foo", "0.1", "TestAuthor");
Plugin created = new Plugin(createdDto.getUuid(), createdDto.getName(), createdDto.getVersion(), createdDto.getAuthor());
pluginRepository.saveAndFlush(created);
pluginRepository.findAll().forEach(plugin -> System.out.print(plugin.toString()));
try {
Plugin plugin = pluginRepository.findById(createdDto.getUuid());
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(pluginService.fetchPlugin(createdDto.getUuid()).toString());
assertEquals(pluginService.fetchPlugin(createdDto.getUuid()), created);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<PluginDTO> response = restTemplate.getForEntity(resourceUrl + createdDto.getUuid(), PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
}
#After
public void tearDown() {
pluginRepository.deleteAllInBatch();
}
}
System.out.println(pluginRepository.findById(createdDto.getUuid()).get().toString()); // this line
assertEquals(pluginService.fetchPlugin(createdDto.getUuid()), created);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<PluginDTO> response = restTemplate.getForEntity(resourceUrl + createdDto.getUuid(), PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
}
Even though the fixed values are set by the createdDto object it doesn't return it and I can see the values are in the database as well. This is what it returns...
20a246e8-7b74-4081-bb62-6911b8ef43ef:Foo:0.1:TestAuthor
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at net.ihq.plugin.controller.PluginServiceIntegrationTest.getPluginTest(PluginServiceIntegrationTest.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I am very stumped as I don't understand why it can save the object but can't get it back with the same fixed values I set it with, but it is actually there from me print the list of objects in the database on the line before the error occurs.
Repository
#Repository
public interface PluginRepository extends JpaRepository<Plugin, UUID> {
#Query(value = "SELECT * FROM plugins WHERE name=?", nativeQuery = true)
Plugin findByName(String name);
}
Entity
#Data
#Entity
#Table(name = "plugins")
#NoArgsConstructor
public class Plugin {
#Id
#Convert(converter = UUIDConverter.class)
#Column(unique = true, updatable = false, length = 36)
private UUID uuid;
private String name;
private String version;
private String author;
public Plugin(UUID uuid, String name, String version, String author) {
this.uuid = uuid;
this.name = name;
this.version = version;
if (author == null) author = "JoeTAMatthews";
this.author = author;
}
public Plugin(String name, String version, String author) {
this(UUID.randomUUID(), name, version, author);
}
public void update(PluginDTO updated) {
this.name = updated.getName();
this.version = updated.getVersion();
this.author = updated.getAuthor();
}
#Override
public String toString() {
return uuid.toString() + ":" + name + ":" + version + ":" + author;
}
}
Sorry for the inconvenience but the reason it doesn't work is because the UUID type is not supported in the database, so all I had to do was get the string type of the uuid to actually get a result because of my UUIDConverter, thanks for all your help.

How to resolve this error TransactionException: commit failed?

i have a Post request ajax like this :
$.ajax({
"url":serverPath+"/taxiws/clients",
"type": "POST",
contentType: "application/json",
dataType: "text",
"data": JSON.stringify(obj),
"success": function(data) {
console.log("success!!!");
$("#LoadingBackgroundPopup").hide();
window.location.href="reservationclient.html";
},"error": function(error) {
console.log(error);
}
});
method Post in web service:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json, UriComponentsBuilder uriBuilder) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
System.out.println("hello post");
try {
Client client = Client.fromJsonToClient(json);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(client.getPassword());
client.setPassword(hashedPassword);
System.out.println("Passowrd hashé "+hashedPassword);
client.persist();
RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
headers.add("Location",uriBuilder.path(a.value()[0]+"/"+client.getIdclient().toString()).build().toUriString());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
but when i excute this requet i found this problem :
!JavaScript LOG: {"ERROR":org.hibernate.TransactionException: commit failed; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: commit failed"}
i added this command line e.getStackTrace(); in my web service ,i found this issue:
2016-04-14 11:56:57,043 [http-bio-8080-exec-5] ERROR org.springframework.transaction.aspectj.AnnotationTransactionAspect - Application exception overridden by rollback exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
at org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect.ajc$afterThrowing$org_springframework_orm_jpa_aspectj_JpaExceptionTranslatorAspect$1$18a1ac9(JpaExceptionTranslatorAspect.aj:33)
at com.binov.webservice.web.Client.persist_aroundBody26(Client.java:243)
at com.binov.webservice.web.Client$AjcClosure27.run(Client.java:1)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:59)
at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:65)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:63)
at com.binov.webservice.web.Client.persist(Client.java:241)
at com.binov.webservice.ClientController.createFromJson(ClientController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.filters.CorsFilter.handleSimpleCORS(CorsFilter.java:302)
at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:170)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy36.persist(Unknown Source)
... 57 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 63 more
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "idclient" violates not-null constraint
Détail : Failing row contains (null, 04-04-2016, dd#mail.com, dd, $2a$10$FXBRGcoZ3uFAD649LDgfMucLXveFDAF1NyrlCvdY6gjpUgpa/gfkO, dd, client, 1234567890, dd).
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 84 more
my classe client.java
package com.binov.webservice.web;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import java.util.Collection;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
#Entity
#Table(schema = "public",name = "client")
#Configurable
public class Client {
#Column(name = "datenaissance", length = 255)
private String datenaissance;
#Column(name = "email", length = 255)
private String email;
#Column(name = "nom", length = 255)
private String nom;
#Column(name = "password", length = 255)
private String password;
#Column(name = "prenom", length = 255)
private String prenom;
#Column(name = "role", length = 255)
private String role;
#Column(name = "telephone", length = 255)
private String telephone;
#Column(name = "username", length = 255)
private String username;
public String getDatenaissance() {
return datenaissance;
}
public void setDatenaissance(String datenaissance) {
this.datenaissance = datenaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idclient")
private Integer idclient;
public Integer getIdclient() {
return this.idclient;
}
public void setIdclient(Integer id) {
this.idclient = id;
}
#PersistenceContext
transient EntityManager entityManager;
public static final List<String> fieldNames4OrderClauseFilter = java.util.Arrays.asList("");
public static final EntityManager entityManager() {
EntityManager em = new Client().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public String toJson() {
return new JSONSerializer()
.exclude("*.class").serialize(this);
}
public String toJson(String[] fields) {
return new JSONSerializer()
.include(fields).exclude("*.class").serialize(this);
}
public static Client fromJsonToClient(String json) {
return new JSONDeserializer<Client>()
.use(null, Client.class).deserialize(json);
}
public static String toJsonArray(Collection<Client> collection) {
return new JSONSerializer()
.exclude("*.class").serialize(collection);
}
public static String toJsonArray(Collection<Client> collection, String[] fields) {
return new JSONSerializer()
.include(fields).exclude("*.class").serialize(collection);
}
public static Collection<Client> fromJsonArrayToClients(String json) {
return new JSONDeserializer<List<Client>>()
.use("values", Client.class).deserialize(json);
}
public static long countClients() {
return entityManager().createQuery("SELECT COUNT(o) FROM Client o", Long.class).getSingleResult();
}
public static List<Client> findAllClients() {
return entityManager().createQuery("SELECT o FROM Client o", Client.class).getResultList();
}
public static List<Client> findAllClients(String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Client o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Client.class).getResultList();
}
// find a client with her username and password
// public static List<Client> findClientByUsernamePassword(String username,String password)
// {
// // TODO Auto-generated method stub
// if((username==null) && (password==null))return null;
// return entityManager().createQuery("SELECT o FROM Client o where o.username=:username and o.password=:password", Client.class).setParameter("username", username).setParameter("password", password).getSingleResult();
// }
//find a cient by username
public static List<Client> findClientByUsernamePassword(String username)
{
// TODO Auto-generated method stub
if((username==null))return null;
return (List<Client>) entityManager().createQuery("SELECT o FROM Client o WHERE o.username=:username",Client.class).setParameter("username", username).getResultList();
}
public static List<Client> findClientByUsernamePassword(String username2,String password2) {
// TODO Auto-generated method stub
return entityManager().createQuery("SELECT o FROM Client o where o.username=:username and o.password=:password", Client.class).setParameter("username", username2).setParameter("password", password2).getResultList();
}
public static Client findClient(Integer idclient) {
if (idclient == null) return null;
return entityManager().find(Client.class, idclient);
}
public static List<Client> findClientEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Client o", Client.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
public static List<Client> findClientEntries(int firstResult, int maxResults, String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Client o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Client.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
#Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
#Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Client attached = Client.findClient(this.idclient);
this.entityManager.remove(attached);
}
}
#Transactional
public void flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
#Transactional
public void clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
#Transactional
public Client merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Client merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
public String toString() {
return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames("Client").toString();
}
}
please ,How can I fix this issue?

Exception while dispatching incoming RPC call - GWT 2.6

I'm working with a GWT(2.6) project together with Spring using "gwtrpc-spring" lib.
I'm trying to send a POJO from server to client, I get this POJO instance getting a Spring bean, and works well, but when I try to send it to client, I got this exception:
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.client.rpc.SerializationException: Type 'java.lang.IllegalArgumentException' was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer.For security purposes, this type will not be serialized.: instance = java.lang.IllegalArgumentException: Unable to find public method: setName with 0 params.
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:667)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:130)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:153)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:587)
at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:605)
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:393)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:545)
at org.gwtrpcspring.RemoteServiceDispatcher.invokeAndEncodeResponse(RemoteServiceDispatcher.java:100)
at org.gwtrpcspring.RemoteServiceDispatcher.processCall(RemoteServiceDispatcher.java:64)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:305)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:68)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:745)
My POJO is:
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
public class ApplicationItem implements Serializable, IsSerializable
{
private static final long serialVersionUID = 1L;
private long id;
private String name;
private String path;
private String grant;
private String icon;
public ApplicationItem(){}
public void setId(long id)
{
this.id = id;
}
public long getId()
{
return id;
}
public void setName()
{
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setPath(String path)
{
this.path = path;
}
public String getPath()
{
return path;
}
public void setGrant(String grant)
{
this.grant = grant;
}
public String getGrant()
{
return grant;
}
public void setIcon(String icon)
{
this.icon = icon;
}
public String getIcon()
{
return icon;
}
#Override
public String toString()
{
return "ApplicationItem: ["+this.id+", "+this.name+", "+this.path+", "+this.grant+", "+this.icon+"]";
}
}
I really appreciate your help.

invalid hex number ora-01465

i have this query in my code. i am trying to isert a image into table in the last column(blob). it is showing invalid hex number. can anybody help me out of this?
#ManagedBean(name="userprofile",eager=true)
#SessionScoped
public class Profile {
#ManagedProperty("#{jdbcTemplate}")
public JdbcTemplate jdbcTemplate;
private String firstName,lastName,email,description;
private UploadedFile photo1;
private int contactNumber;
private String insertQry;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public UploadedFile getPhoto1() {
return photo1;
}
public void setPhoto1(UploadedFile photo1) {
this.photo1 = photo1;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public void insertProfile() throws Exception{
InputStream is=photo1.getInputstream();
System.out.println(is);
insertQry="insert into profile
values('"+getFirstName()+"','"+getLastName()+"','"+getContactNumber()+"',
'"+getEmail()+"','"+getDescription()+"','"+utl_raw.cast_to_raw(is)+"')";
System.out.println(insertQry);
int num=jdbcTemplate.update(insertQry);
System.out.println(num);
}
}
any kind of response is appreciated in advance.
This error:
invalid hex number ora-01465
means that your not sending an Hexa.
Solution:
Please try to convert InputStream to Hexa before insert image.

failed to lazily initialize a collection

I'm developing a restful web service for my database. I'm using jpa to retriving data from the db and spring for the architecture. I already tested the architecture with the basic dao queries (findById, save...) and it works perfectly. Then in the dao implementation I added a new method wich basically execute a query that is tested directly on the mysql db (and it worked)
public List<PositionHistory> findByFavUserGBuser(Integer favoriteUserId,
Integer pageNumber, Integer rowsPerPage, String usernameFilter) {
String queryString="" +
"SELECT ph.* " +
"FROM user u, position_history ph, spot s " +
"WHERE " +
"ph.date IN (SELECT MAX(ph2.date) FROM position_history ph2 GROUP BY ph2.user_iduser) and " +
"s.id_spot=ph.spot_idspot and " +
"u.id_user=ph.user_iduser and ";
if (usernameFilter!=null)
queryString+="u.username like '%:usernameFilter%' and ";
queryString+="" +
"ph.user_iduser IN (SELECT ALL fu.user_iduserto FROM favorite_user fu WHERE fu.user_iduserfrom=:favoriteUserId) " +
"GROUP BY ph.user_iduser " +
"LIMIT :startLimit,:rowsPerPage";
Query query = entityManager.createNativeQuery(queryString,PositionHistory.class);
query.setParameter("favoriteUserId", favoriteUserId);
query.setParameter("startLimit", pageNumber*rowsPerPage);
query.setParameter("rowsPerPage", rowsPerPage);
if (usernameFilter!=null)
query.setParameter("usernameFilter", usernameFilter);
return query.getResultList();
}
and then I created a controller to retrive data as follow:
#Controller
#Transactional
public class MyController {
#Autowired
public DaoPositionHistory dph;
#Transactional
#RequestMapping(value = "/getData/{id}/", method = RequestMethod.POST)
#ResponseBody
public List<PositionHistory> home(#PathVariable int id) {
List<PositionHistory> resultlist=(List<PositionHistory>) dph.findByNearestPositionGBuser(id, 0, 10, null, null, null);
return resultlist;
}
}
but when i call the service i get the following error:
ERROR: org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.windy.spring.data.User.favoriteSports, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.windy.spring.data.User.favoriteSports, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:272)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:45)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
at org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:122)
at org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:71)
at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1613)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:142)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:137)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:81)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:94)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:73)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
I can not understand why I get this error if i declared the methos as #transactional? Any idea on how I can solve the problem?
Here is also my User class
#XmlRootElement
#Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id_user")
private int idUser;
private String cellphone;
private String email;
#Lob()
private byte[] foto;
private String name;
private String notes;
private String password;
private String surname;
private String username;
//bi-directional many-to-one association to FavoriteSport
#OneToMany(mappedBy="user")
private List<FavoriteSport> favoriteSports;
//bi-directional many-to-one association to FavoriteSpot
#OneToMany(mappedBy="user")
private List<FavoriteSpot> favoriteSpots;
//bi-directional many-to-one association to FavoriteUser
#OneToMany(mappedBy="user2")
private List<FavoriteUser> favoriteUsers;
//uni-directional many-to-one association to Role
#ManyToOne
#JoinColumn(name="role_idrole")
private Role role;
//bi-directional many-to-one association to UserAccount
#OneToMany(mappedBy="user")
private List<UserAccount> userAccounts;
public User() {
}
public int getIdUser() {
return this.idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getCellphone() {
return this.cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public byte[] getFoto() {
return this.foto;
}
public void setFoto(byte[] foto) {
this.foto = foto;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSurname() {
return this.surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public List<FavoriteSport> getFavoriteSports() {
return this.favoriteSports;
}
public void setFavoriteSports(List<FavoriteSport> favoriteSports) {
this.favoriteSports = favoriteSports;
}
public List<FavoriteSpot> getFavoriteSpots() {
return this.favoriteSpots;
}
public void setFavoriteSpots(List<FavoriteSpot> favoriteSpots) {
this.favoriteSpots = favoriteSpots;
}
public List<FavoriteUser> getFavoriteUsers() {
return this.favoriteUsers;
}
public void setFavoriteUsers(List<FavoriteUser> favoriteUsers) {
this.favoriteUsers = favoriteUsers;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
public List<UserAccount> getUserAccounts() {
return this.userAccounts;
}
public void setUserAccounts(List<UserAccount> userAccounts) {
this.userAccounts = userAccounts;
}
}
I figured this out from reading the other answers to your question. Just in case anyone needs it here is an example:
#Override
public OriginServer get(Integer id){
OriginServer server = (OriginServer) sessionFactory
.getCurrentSession().get(OriginServer.class, id);
Hibernate.initialize(server.getPools());
return server;
}
In this example 'getPools' is a #OneToMany relationship from OriginServer.
The stacktrace clearly shows that the exception occurs after the controller method has completed (and the transaction closed).
So either use an extended persistence context (where sessions live longer than transactions), access the lazy collection before the controller method returns, modify your DAO or mapping to load the collection eagerly, or don't return an object containing that collection.
Your error is because you are not initializing entity associations in your DAO, and then the Jackson converter is trying to convert all associations in your return object to JSON. Since the associations are not initialized, the error is thrown since your Controller doesn't have a handle to the Hibernate Session.
See my answer here for how to correct: Spring #ResponseBody Json Cyclic Reference

Resources