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.
Related
I have created Bean which is a composite bean(hold instances of other beans).Declared with notation so that it treats the object data as xml data.The below villageInvigilator bean holds person,user and address objects.I have declared those classes with xml annotations(xml binding).Now am trying to send the xml data over post rest call to dump the data into ML but its been failed due to the below error.Can someone help me whats went wrong in the below code.
com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java class com.sun.jersey.multipart.MultiPart, and Java type class com.sun.jersey.multipart.MultiPart, and MIME media type multipart/mixed; boundary=Boundary_2_1591997445_1586182536010 was not found
at com.sun.jersey.api.client.RequestWriter$RequestEntityWriterImpl.<init>(RequestWriter.java:199) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.api.client.RequestWriter.getRequestEntityWriter(RequestWriter.java:248) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.getHttpEntity(ApacheHttpClient4Handler.java:241) ~[jersey-apache-client4-1.17.jar:1.17]
at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.getUriHttpRequest(ApacheHttpClient4Handler.java:197) ~[jersey-apache-client4-1.17.jar:1.17]
at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:153) ~[jersey-apache-client4-1.17.jar:1.17]
at com.marklogic.client.impl.DigestChallengeFilter.handle(DigestChallengeFilter.java:34) ~[marklogic-client-api-4.0.1.jar:na]
at com.sun.jersey.api.client.filter.HTTPDigestAuthFilter.handle(HTTPDigestAuthFilter.java:494) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.api.client.Client.handle(Client.java:652) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) ~[jersey-client-1.19.4.jar:1.19.4]
at com.sun.jersey.api.client.WebResource$Builder.put(WebResource.java:539) ~[jersey-client-1.19.4.jar:1.19.4]
at com.marklogic.client.impl.JerseyServices.putPostDocumentImpl(JerseyServices.java:1503) ~[marklogic-client-api-4.0.1.jar:na]
at com.marklogic.client.impl.JerseyServices.putDocument(JerseyServices.java:1199) ~[marklogic-client-api-4.0.1.jar:na]
at com.marklogic.client.impl.DocumentManagerImpl.write(DocumentManagerImpl.java:919) ~[marklogic-client-api-4.0.1.jar:na]
at com.marklogic.client.impl.DocumentManagerImpl.write(DocumentManagerImpl.java:757) ~[marklogic-client-api-4.0.1.jar:na]
at com.marklogic.client.impl.DocumentManagerImpl.write(DocumentManagerImpl.java:701) ~[marklogic-client-api-4.0.1.jar:na]
at com.kc.serviceImplementation.VillageInspectorOperationsImpl.villageInspectorRegistration(VillageInspectorOperationsImpl.java:112) ~[classes/:na]
at com.kc.web.VillageInspectorRESTController.createUser(VillageInspectorRESTController.java:37) ~[classes/:na]
package com.kissan.datatypes;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "villageInspector")
public class VillageInspector {
private String id;
private Person person;
private User user;
private Address address;
public VillageInspector() {
}
public VillageInspector(String id, Person person, User user, Address address) {
super();
this.id = id;
this.person = person;
this.user = user;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Implementation code:
public void villageInspectorRegistration(VillageInspector villageInspector) {
// TODO Auto-generated method stub
DocumentMetadataHandle metadata = new DocumentMetadataHandle();
List<String> str = new ArrayList<String>();
str.add("villageInspectors");
metadata.getCollections().addAll(str);
JAXBHandle<VillageInspector> contentHandle = getUserDetailsHandle();
contentHandle.set(villageInspector);
xmlDocumentManager.write(commonUtils.getDocId(villageInspector.getId(),objectType), metadata, contentHandle);
}
private JAXBHandle<VillageInspector> getUserDetailsHandle() {
try {
JAXBContext context = JAXBContext.newInstance(VillageInspector.class);
return new JAXBHandle<VillageInspector>(context);
} catch (JAXBException e) {
throw new RuntimeException("Unable to create Village Inspector JAXB context", e);
}
}
I am using Spring Boot and MongoDB and I am able to store a document in MongoDB successfully. When I was trying to insert a second document, it is showing duplicatekeyexception. The total message of exception is as follows:
com.mongodb.DuplicateKeyException: Write failed with error code 11000
and error message 'E11000 duplicate key error collection:
Football_Admin.SignUp index: id dup key: { : 0 }'
The code is as follows:
SignUpRepository.java
package com.admin.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.admin.Model.SignUp;
#Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{
}
Controller
#Controller
#RequestMapping("/SignIn_Up")
public class HomeController {
#Autowired
SignUpRepository repository;
#RequestMapping(value = "/addadmin", method = RequestMethod.POST)
public String addAdmin(#ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
String originalPassword = sign.getPassword();
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
String email = sign.getEmail();
String fullname = sign.getFullName();
try {
sign.setEmail(email);
sign.setFullName(fullname);
sign.setPassword(generatedSecuredPasswordHash);
repository.save(sign);
}
catch (DuplicateKeyException e) {
e.printStackTrace();
}
System.out.println(generatedSecuredPasswordHash);
System.out.println("Email name is:"+sign.getEmail());
System.out.println("Full Name is:"+sign.getFullName());
System.out.println("Password is:"+sign.getPassword());
return "welcome";
}
Entity
package com.admin.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="SignUp")
public class SignUp {
#Id
private int id;
private String fullName;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return id+""+fullName+""+password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
MongoDb driver don't know how to create a unique Id of type int when inserting so you received unique index exception
So either you manually create and maintain your index (quite hard) or change your id field type to ObjectId
public List<Bean> getList() {
List<Bean> beanList = new ArrayList<Bean>();
// some code here
while(hasNext()) {
// some code here
Bean bean = new Bean();
listing(bean, beanList);
}
// sort by age bean here before returning
return beanList
}
public void listing(Bean bean, List<Bean> beanList) {
//some code here
bean.setName(var1);
bean.setAddress(var2);
bean.setAge(var3);
beanList.add(bean)
}
I need to sort the arraylist based on the age.
I tried using Collectors but I'm not sure how to implement it with those code yet.
Thank you.
You need implement Comparator interface. In this case your implemnetation would be
public class BeanAgeComparator implements Comparator<Bean> {
int compare(Bean o1,Bean o2) {
return o1.getAge() - o2.getAge();
}
}
Then you can sort the List using Collections.sort(beanList, new BeanAgeComparator());
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class BinarySearch{
public static void main(String s[]) {
List<Bean> beanList=new BinarySearch().getList(10);
for(Bean bean:beanList){System.out.println(bean.getAge());}
}
public List<Bean> getList(int size) {
List<Bean> beanList = new ArrayList<Bean>();
int i=0;
while(i<size) {
Bean bean = new Bean();
listing(bean, beanList);
i++;
}
Comparator<Bean> c=new Comparator<Bean>(){
#Override
public int compare(Bean bean1, Bean bean2) {
return bean1.getAge()-bean2.getAge();
}};
Collections.sort(beanList,c);
return beanList;
}
Random r=new Random();
public void listing(Bean bean, List<Bean> beanList) {
bean.setName("name");
bean.setAddress("address");
bean.setAge(r.nextInt(81)+18);
beanList.add(bean);
}
}
class Bean {
String name;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
int age;
}
Or u can implement comparable interface in your Bean class-
public class SortedList{
public static void main(String s[]) {
List<Bean> beanList=new SortedList().getList(10);
for(Bean bean:beanList){System.out.println(bean.getAge());}
}
public List<Bean> getList(int size) {
List<Bean> beanList = new ArrayList<Bean>();
int i=0;
while(i<size) {
Bean bean = new Bean();
listing(bean, beanList);
i++;
}
Collections.sort(beanList);
return beanList;
}
Random r=new Random();
public void listing(Bean bean, List<Bean> beanList) {
bean.setName("name");
bean.setAddress("address");
bean.setAge(r.nextInt(81)+18);
beanList.add(bean);
}
}
class Bean implements Comparable<Bean>{
String name;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
int age;
#Override
public int compareTo(Bean bean) {
return this.getAge()-bean.getAge();
}
}
Here is my #Controller:
#RequestMapping(value = "/add")
public void addMember(Member member) {
// ... ...
}
here is Member class:
class Member {
private Integer id;
private String username;
// ... ...
}
And here is the request url:
/add?memberId=1&username=bruce
How can I bind the memberId parameter to Member.id field?
Thanks!
If you don't want to use
#RequestMapping(value = "/add")
public void addMember(#RequestParam(value = "username") String username, ...) {
Member member = new Member(username, ...)
// ...
}
you can implement HandlerMethodArgumentResolver:
public class MemberHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter parameter) {
return Member.class.equals(parameter.getParameterType());
}
#Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String username = webRequest.getParameter("username");
...
return new Member(username, ...);
}
}
And in config:
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean id="memberResolver" class="com.company ... MemberHandlerMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
or JavaConfig:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
...
#Override
public void addArgumentResolvers(List<Handlermethodargumentresolver> argumentResolvers) {
argumentResolvers.add(new MemberHandlerMethodArgumentResolver());
}
}
IMHO the simplest way to do that is to use an additional setter in Member class :
class Member {
private Integer id;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setMemberId(Integer memberId) { // this one should to the trick
this.id = memberId;
}
// ... ...
}
You can use #JsonProperty Annotation for it.Like below.
class Member {
#JsonProperty("memberId")
private Integer id;
private String username;
// ... ...
}
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