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);
}
}
Related
I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!
Basically, I am trying to establish a relationship between my two tables using spring boots.
And the relationship which I had used was the #onetoone and #onetomany relationship.
But after building the relationship and creating the table in MySQL whenever I run the program my foreign key is not updating.
The relationship is one user can have many contacts. I have tried unidirectional as well as bidirectional mapping but it is not working.
I want in contact table there will be a separate column for the foreign key. Based on that key I will show all contacts for that particular user.
This is my contact entity...
package com.example.jpa.contactEntities;
#Entity
#Table(name = "Contact")
public class ContactEntities {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long c_id;
private String c_name;
private String second_c_name;
private String c_work;
private String c_emali;
private String c_phone;
private String c_image;
#Column(length = 5000)
private String c_description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "contact_id")
private UserEntities userEntities;
public ContactEntities() {
super();
}
public ContactEntities(long c_id, String c_name, String second_c_name, String c_work, String c_emali,
String c_phone, String c_image, String c_description, UserEntities userEntities) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.second_c_name = second_c_name;
this.c_work = c_work;
this.c_emali = c_emali;
this.c_phone = c_phone;
this.c_image = c_image;
this.c_description = c_description;
this.userEntities = userEntities;
}
public long getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getSecond_c_name() {
return second_c_name;
}
public void setSecond_c_name(String second_c_name) {
this.second_c_name = second_c_name;
}
public String getC_work() {
return c_work;
}
public void setC_work(String c_work) {
this.c_work = c_work;
}
public String getC_emali() {
return c_emali;
}
public void setC_emali(String c_emali) {
this.c_emali = c_emali;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getC_image() {
return c_image;
}
public void setC_image(String c_image) {
this.c_image = c_image;
}
public String getC_description() {
return c_description;
}
public void setC_description(String c_description) {
this.c_description = c_description;
}
public UserEntities getUserEntities() {
return userEntities;
}
public void setUserEntities(UserEntities userEntities) {
this.userEntities = userEntities;
}
#Override
public String toString() {
return "ContactEntities [c_id=" + c_id + ", c_name=" + c_name + ", second_c_name=" + second_c_name + ", c_work="
+ c_work + ", c_emali=" + c_emali + ", c_phone=" + c_phone + ", c_image=" + c_image + ", c_description="
+ c_description + ", userEntities=" + userEntities + "]";
}
}
this is my user entity...
package com.example.jpa.userEntities;
#Entity
#Table(name = "UserEntities")
public class UserEntities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#NotBlank
#Size(min = 2, max = 20)
private String userName;
#NotBlank
#Column(unique = true)
#Email(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
private String userEmail;
#NotNull(message = "password should not be blank")
private String userPass;
private boolean enable;
private String role;
#Column(length = 500)
private String userAbout;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntities", orphanRemoval = true)
private List<ContactEntities> contactList = new ArrayList<>();
public UserEntities() {
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getRoll() {
return role;
}
public void setRoll(String role) {
this.role = role;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public List<ContactEntities> getContactList() {
return contactList;
}
public void setContactList(List<ContactEntities> contactList) {
this.contactList = contactList;
}
#Override
public String toString() {
return "UserEntities [userId=" + userId + ", userName=" + userName + ", userEmail=" + userEmail + ", userPass="
+ userPass + ", enable=" + enable + ", role=" + role + ", userAbout=" + userAbout + ", contactList="
+ contactList + "]";
}
}
Repository of Contact
package com.example.jpa.repo;
import java.util.List;
import com.example.jpa.contactEntities.ContactEntities;
public interface ContactRepo extends JpaRepository<ContactEntities, Integer> {
#Query("from ContactEntities as c where c.userEntities.userId=:u_Id")
public List<ContactEntities> findContactsByUser(#Param("u_Id") long l);
}
Repository of User
package com.example.jpa.repo;
import com.example.jpa.userEntities.UserEntities;
#EnableJpaRepositories
public interface UserRepository extends JpaRepository<UserEntities, Integer> {
#Query("select u from UserEntities u where u.userEmail=:userEmail")
public UserEntities getUserByUserName(#Param("userEmail") String userEmail);
}
User controller
package com.example.jpa.controller;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private ContactRepo contactRepo;
#ModelAttribute
public void addCommonData(Model model, Principal principal) {
String username = principal.getName();
System.out.println("UserName:-" + username);
UserEntities userEntities = this.userRepository.getUserByUserName(username);
System.out.println("User:- " + userEntities);
model.addAttribute("userEntities", userEntities);
}
//dash board home
#RequestMapping("/index")
public String dashboard(Model model, Principal principal) {
return "normal/user_dashboard";
}
// open add form handler
#GetMapping("/add-contact")
public String openAddContactForm(Model model) {
model.addAttribute("title", "Add contact");
model.addAttribute("contactEntitie", new ContactEntities());
return "normal/add_contact";
}
// processing and contact form
#PostMapping("/upload")
public String processContact(#ModelAttribute ContactEntities contactEntitie,
#RequestParam("userImage") MultipartFile multipartFile, Principal principal, Model model,
HttpSession session) {
try {
model.addAttribute("contactEntitie", new ContactEntities());
String name = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(name);
userEntities.getContactList().add(contactEntitie);
// processing and uploading file....
if (multipartFile.isEmpty()) {
System.out.println("File is empty");
} else {
// upload the the file and update
contactEntitie.setC_image(multipartFile.getOriginalFilename());
File saveFile = new ClassPathResource("static/img").getFile();
// bring the folder path...
Path path = Paths
.get(saveFile.getAbsolutePath() + File.separator + multipartFile.getOriginalFilename());
Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image is uploaded");
}
userRepository.save(userEntities);
System.out.println("Datas are :" + contactEntitie);
// message success
session.setAttribute("message", new Messages("Your Contact is added !!! Add more...", "success"));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
// error message
session.setAttribute("message", new Messages("Something went wrong !!! Try Again", "danger"));
}
return "normal/add_contact";
}
// show Contact handler
#GetMapping("/show-contacts")
public String showContact(Model model, Principal principal) {
model.addAttribute("title", "Show Contacts");
String userName = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(userName);
List<ContactEntities> contactList = contactRepo.findContactsByUser(userEntities.getUserId());
model.addAttribute("contactList", contactList);
return "normal/show_contacts";
}
}
All configuration class
User Details configuration
package com.example.jpa.Myconfiguration;
public class UserDetailsServiceImple implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// fetching data from DB
UserEntities userEntities = userRepository.getUserByUserName(username);
if (userEntities == null) {
throw new UsernameNotFoundException("Could not found user !!!");
}
CustomUserDetails customUserDetails = new CustomUserDetails(userEntities);
return customUserDetails;
}
}
package com.example.jpa.Myconfiguration;
public class CustomUserDetails implements UserDetails {
private UserEntities userEntities;
public CustomUserDetails(UserEntities userEntities) {
super();
this.userEntities = userEntities;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userEntities.getRoll());
return List.of(simpleGrantedAuthority);
}
#Override
public String getPassword() {
return userEntities.getUserPass();
}
#Override
public String getUsername() {
return userEntities.getUserEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Application property:-
#Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/smartcontact
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.NonRegisteringDriver
spring.jpa.properties.hibernate.dilact=org.hibernate.dialect.Mysql8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
--------------------------------------Table 1--------------------------------------
#Entity
#Table(name = "student_details")
public class StudentDetails {
#Id
private Long studentId;
private String firstName;
private String lastName;
private String fatherName;
// with getter and setters
}
-------------------------------------Table 2---------------------------------
#Entity
#Table(name = "student_marks")
public class StudentMarks {
#Id
private Long studentId;
private int Maths;
private int English;
private int Computer;
// with getter and setters
}
------------------------------------class which combine these two table------------------
public class StudentReportData {
#Id
private Long studentId;
private String studentName
private String fatherName;
private int Maths;
private int English;
private int Computer;
//with getter and setters
}
-----------------------------------Service Class---------------------------
#Service
public class StudentService {
public ApiResponce<List<StudentReportData>> getStudentData() {
ApiResponce<List<StudentReportData>> responce = new ApiResponce();
Status status = new Status();
status setSuccess(true);
try {
List<StudentReportData> studentList = new ArrayList<StudentReportData>();
List<StudentMarks> findAll = studentMarksRepository.findAll();
for(StudentMarks sm : findAll) {
StudentReportData studentData = new StudentReportData();
BeanUtils.copyProperties(sm, studentData);
StudentDetails studentDetailsData = studentDetailsRepository.findByStudentId(sm.getStudentId());
studentData.setStudentName(studentDetailsData.getFirstName()+" "+studentDetailsData.getLastName());
studentList.add(studentData);
}
response.setData(studentList);
} catch (Exception ex) {
ex.printStackTrace();
ErrorData errorData = new ErrorData();
errorData.setErrorCode("ERR003");
errorData.setErrorMessage("Internal Server Error");
status.setErrorData(errorData);
status.setSuccess(false);
}
response.setStatus(status);
return response;
}
public ByteArrayInputStream load() {
ByteArrayInputStream in = ExcelHelper.studentreportToExcel(studentList);
return in;
}
}
I want to pass this studentList as an argument to the function studentReportToExcel from the function load. How can I get that List Inside the load function.
Add it as a class attribute, something like:
#Service
public class StudentService {
private List<StudentReportData> studentList; // class attribute to add
public ApiResponce<List<StudentReportData>> getStudentData() {
ApiResponce<List<StudentReportData>> responce = new ApiResponce();
Status status = new Status();
status setSuccess(true);
try {
studentList = new ArrayList<StudentReportData>(); // line changed
List<StudentMarks> findAll = studentMarksRepository.findAll();
for(StudentMarks sm : findAll) {
StudentReportData studentData = new StudentReportData();
BeanUtils.copyProperties(sm, studentData);
StudentDetails studentDetailsData = studentDetailsRepository.findByStudentId(sm.getStudentId());
studentData.setStudentName(studentDetailsData.getFirstName()+" "+studentDetailsData.getLastName());
studentList.add(studentData);
}
response.setData(studentList);
} catch (Exception ex) {
ex.printStackTrace();
ErrorData errorData = new ErrorData();
errorData.setErrorCode("ERR003");
errorData.setErrorMessage("Internal Server Error");
status.setErrorData(errorData);
status.setSuccess(false);
}
response.setStatus(status);
return response;
}
public ByteArrayInputStream load() {
ByteArrayInputStream in = ExcelHelper.studentreportToExcel(studentList);
return in;
}
}
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
What ever I try, I cannot delete a user entity when I call delete() from my userService class. I get an exception java.lang.IllegalArgumentException: Entity must be managed to call remove: com.blackbox.genesis.entities.User#30168a, try merging the detached and try the remove again. I'm obviously doing something wrong - despite merging, but I can't see what. Everything else works fine - I can create and update user entities without any problem.
Regards
My entity class;
#Entity
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = "EMAIL")})
public class User implements Serializable {
#Id
#Column(name="username", length=50)
private String username;
#OneToOne(cascade = {CascadeType.ALL})
private Password password;
private boolean enabled;
private int serial;
private String email;
#Version
private int version;
#ElementCollection(targetClass=Authority.class)
#CollectionTable(name="USER_AUTHORITY")
private List<Authority> authorities;
#OneToMany(mappedBy="user", fetch=FetchType.LAZY, cascade=CascadeType.ALL, ``orphanRemoval=true)
private Set<License> licenses;
private static final long serialVersionUID = 1L;
public User() {
super();
this.authorities = new ArrayList<Authority>();
}
.... getters/setters.
My DAO class;
#Repository
public class UserJpaController {
#PersistenceContext
EntityManager em;
protected static final Logger logger = Logger.getLogger("com.blackbox.genesisng.entities.UsersJpaController");
public void create(User user) throws PreexistingEntityException, Exception {
if (findUser(user.getUsername()) != null) {
throw new PreexistingEntityException("Users " + user + " already exists.");
}
em.persist(user);
em.flush();
}
public void edit(User user) throws NonexistentEntityException, Exception {
user = em.merge(user);
em.flush();
}
public void destroy(String id) throws NonexistentEntityException {
User user = em.find(User.class, id);
user = em.merge(user);
em.remove(user);
}
public List<User> findUserEntities() {
return findUserEntities(true, -1, -1);
}
public List<User> findUserEntities(int maxResults, int firstResult) {
return findUserEntities(false, maxResults, firstResult);
}
private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
Query q = em.createQuery("select object(o) from User as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
}
public User findUser(String id) {
return em.find(User.class, id);
}
public int getUserCount() {
Query q = em.createQuery("select count(o) from User as o");
return ((Long) q.getSingleResult()).intValue();
}
public User findUserByEmail(String email) {
Query q = em.createQuery("select Object(o) from User as o where o.email = :email");
q.setParameter("email", email);
List list = q.getResultList();
if (list.size() == 0) {
return null;
}
return (User) list.get(0);
}
public boolean exists(String id) {
try {
em.getReference(User.class,id);
return true;
}
catch (EntityNotFoundException e) {
return false;
}
}
}
and finally, the relevant portion of my service class
#Service
public class UserService {
#Autowired
UserJpaController dao;
#Autowired
LicenseJpaController licenseDao;
#Transactional
public void delete(UserDTO userDTO) {
if (exists(userDTO.getUserName())){
try {
dao.destroy(userDTO.getUserName());
} catch (NonexistentEntityException e) {
// ignore as the previous test should prevent this.
}
}
}
So sorry, but I'm an idiot! I was not calling the service class that I thought I was. Fixed that and everything works as expected. Once again, sorry folks.
Regards
Remove the
user = em.merge(user);
statement in your DAO destroy method. I am not sure if it causes the probem, but it is not needed because the user is loaded in the statement before.