This is the error shown:
exception
<openjpa-2.3.0-r422266:1540826 fatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while processing registered class "class no.avexis.fjellkam.Models.Cabin".
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1684)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Can't overwrite cause with java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [org.apache.openjpa.util.IntId]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.Throwable.initCause(Throwable.java:457)
org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1324)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1203)
java.lang.ClassLoader.loadClass(ClassLoader.java:411)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
org.apache.openjpa.enhance.no$avexis$fjellkam$Models$Cabin$pcsubclass.pcNewObjectIdInstance(Unknown Source)
org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:140)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1731)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1681)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException
org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1323)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1203)
java.lang.ClassLoader.loadClass(ClassLoader.java:411)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
org.apache.openjpa.enhance.no$avexis$fjellkam$Models$Cabin$pcsubclass.pcNewObjectIdInstance(Unknown Source)
org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:140)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1731)
org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1681)
org.apache.openjpa.meta.ClassMetaData.getPCSubclasses(ClassMetaData.java:376)
org.apache.openjpa.jdbc.meta.MappingRepository.findBaseClassMapping(MappingRepository.java:1539)
org.apache.openjpa.jdbc.meta.MappingRepository.prepareMapping(MappingRepository.java:402)
org.apache.openjpa.meta.MetaDataRepository.preMapping(MetaDataRepository.java:769)
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.java:658)
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataRepository.java:418)
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:389)
org.apache.openjpa.enhance.ManagedClassSubclasser.configureMetaData(ManagedClassSubclasser.java:227)
org.apache.openjpa.enhance.ManagedClassSubclasser.prepareUnenhancedClasses(ManagedClassSubclasser.java:182)
org.apache.openjpa.kernel.AbstractBrokerFactory.loadPersistentTypes(AbstractBrokerFactory.java:312)
org.apache.openjpa.kernel.AbstractBrokerFactory.initializeBroker(AbstractBrokerFactory.java:236)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:212)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
no.avexis.fjellkam.DAO.AdminDAO.getEvents(AdminDAO.java:161)
no.avexis.fjellkam.Controllers.Common.ArticleServlet.doGet(ArticleServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is how I have class file looks like:
package no.avexis.fjellkam.Models;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CABIN")
public class Cabin implements Serializable {
private static final long serialVersionUID = -9160490433220569097L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer cabinID;
private String cabin;
private String title;
private String description;
public Cabin() {
this.cabin = "";
this.title = "";
this.description = "";
}
public Cabin(String cabin, String title, String description) {
this.cabin = cabin;
this.title = title;
this.description = description;
}
public String getCabin() {
return cabin;
}
public void setCabin(String cabin) {
this.cabin = cabin;
}
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 Integer getCabinID() {
return cabinID;
}
}
I keep getting this error for all my classes, and I either must be overlooking something, or I've done something very wrong.
It would seem as though there is an error while parsing the class, or locating the class?
Related
cnv any one help me I dont knoe where make mistake,when i run my
application in chrome in browser when type
http://localhost:8100/currency-converter-feign/from/USD/to/INR/quantity/1000
i got this type of erro
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Fri Jul 17 21:38:29 IST 2020 There was an unexpected error
(type=Internal Server Error, status=500). No message available
java.lang.NullPointerException at
java.math.BigDecimal.multiply(Unknown Source) at
com.main.conteoller.CurrencyconversionController.convertCurencyFfeign(CurrencyconversionController.java:47)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at
currencyconvertercontroller.java
package com.main.conteoller;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.main.Bean.ConversionBean;
import com.main.serviceproxy.CurrencyexchangeserviceProxy;
#RestController
public class CurrencyconversionController {
#Autowired
private CurrencyexchangeserviceProxy proxy;
#GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
public ConversionBean convertCurency(#PathVariable String from,
#PathVariable String to,
#PathVariable BigDecimal quantity) {
Map<String, String>uriVariables= new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
ResponseEntity<ConversionBean>resp = new RestTemplate()
.getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
ConversionBean.class,
uriVariables);
ConversionBean cbresp=resp.getBody();
return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());
}
#GetMapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
public ConversionBean convertCurencyFfeign(#PathVariable String from,
#PathVariable String to,
#PathVariable BigDecimal quantity) {
ConversionBean cbresp=proxy.retrivefromexchange(from, to);
return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());
}
}
currencybean.java
package com.main.Bean;
import java.math.BigDecimal;
public class ConversionBean {
private int id;
private String from;
private String to;
private BigDecimal convermultiple;
private BigDecimal quantity;
private BigDecimal totalCalamount;
private int port;
public ConversionBean() {}
public ConversionBean(int id, String from, String to, BigDecimal convermultiple, BigDecimal quantity,
BigDecimal totalCalamount, int port) {
super();
this.id = id;
this.from = from;
this.to = to;
this.convermultiple = convermultiple;
this.quantity = quantity;
this.totalCalamount = totalCalamount;
this.port = port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public BigDecimal getConvermultiple() {
return convermultiple;
}
public void setConvermultiple(BigDecimal convermultiple) {
this.convermultiple = convermultiple;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalCalamount() {
return totalCalamount;
}
public void setTotalCalamount(BigDecimal totalCalamount) {
this.totalCalamount = totalCalamount;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
currencyexchangeproxy.java
package com.main.serviceproxy;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.main.Bean.ConversionBean;
#FeignClient(name="currency-exchange",url="localhost:8000")
public interface CurrencyexchangeserviceProxy {
#GetMapping("/currency-exchange/from/{from}/to/{to}")
public ConversionBean retrivefromexchange(#PathVariable ("from") String from,
#PathVariable ("to") String to);
}
It is occurs due to mismatch of comumn name in your db table and in
your entity class. Because I use micriservices,I call some exchange
rates from another project by provideing its url in my repository, in
that project i privide same name in my entity class and in my db table
,but i declared diffrent name in my exchange service project. there i
declare conversationmultople and here declare convermultiple
.make sure both name same in db and your bean class
#EnableFeignClient service in your springboot main method
for example
package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
#SpringBootApplication
#EnableFeignClients("com.main.serviceproxy")
public class CurrencyConversionServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CurrencyConversionServiceApplication.class, args);
}
}
I am using custom annotation for form validation in my spring4.2.3 and hibernate5.1.0 based project.
1) My Annotation Interface looks like this
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.rapidtech.rapidtechorganic.custom.logic.UnitConstraintValidator;
#Documented
#Constraint(validatedBy = UnitConstraintValidator.class)
#Target( {ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface IsUnit {
String message() default "Please Enter a valid UNIT e.g. kg,litre,ton";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2) My logic class UnitConstraintValidator looks like this
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.rapidtech.rapidtechorganic.custom.annotation.IsUnit;
public class UnitConstraintValidator implements ConstraintValidator<IsUnit, String> {
#Override
public void initialize(IsUnit unit) {
// TODO Auto-generated method stub
}
#Override
public boolean isValid(String unit, ConstraintValidatorContext cxt) {
if(unit.equals(null) || unit == null){
return false;
}
if(unit.matches("kg|KG|Kg|Litre|litre|lt|ton|Ton")){
return true;
}
return false;
}
}
3) My Model class where I am using custom annotation
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.rapidtech.rapidtechorganic.custom.annotation.IsUnit;
#JsonIgnoreProperties(ignoreUnknown = true)
#Entity
public class Lot implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long lotId;
#Size(min=5,max=30)
private String lotNumber;
#IsUnit
private String lotName;
#OneToOne(cascade = {CascadeType.ALL})
private ProductAvailable productAvailable;
public long getLotId() {
return lotId;
}
public void setLotId(long lotId) {
this.lotId = lotId;
}
public String getLotNumber() {
return lotNumber;
}
public void setLotNumber(String lotNumber) {
this.lotNumber = lotNumber;
}
public String getLotName() {
return lotName;
}
public void setLotName(String lotName) {
this.lotName = lotName;
}
public ProductAvailable getProductAvailable() {
return productAvailable;
}
public void setProductAvailable(ProductAvailable productAvailable) {
this.productAvailable = productAvailable;
}
}
4) My ProductAvailable model class where I am using custom annotation
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.Size;
import com.rapidtech.rapidtechorganic.custom.annotation.IsUnit;
#Entity
public class ProductAvailable implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long productAvailableId;
#Size(min=2,max=30,message="ahha ahha ahha")
private String productAvailableName;
#IsUnit
private String productAvailableUnit;
private double productAvailableUnitTransportationCharge;
private double productAvailableUnitLabourCharge;
private double productAvailableUnitOtherCharge;
private long productAvailableQuantity;
private double productAvailableUnitPrice;
#OneToOne
private Lot lot;
public long getProductAvailableId() {
return productAvailableId;
}
public void setProductAvailableId(long productAvailableId) {
this.productAvailableId = productAvailableId;
}
public String getProductAvailableName() {
return productAvailableName;
}
public void setProductAvailableName(String productAvailableName) {
this.productAvailableName = productAvailableName;
}
public long getProductAvailableQuantity() {
return productAvailableQuantity;
}
public void setProductAvailableQuantity(long productAvailableQuantity) {
this.productAvailableQuantity = productAvailableQuantity;
}
public double getProductAvailableUnitPrice() {
return productAvailableUnitPrice;
}
public void setProductAvailableUnitPrice(double productAvailableUnitPrice) {
this.productAvailableUnitPrice = productAvailableUnitPrice;
}
public String getProductAvailableUnit() {
return productAvailableUnit;
}
public void setProductAvailableUnit(String productAvailableUnit) {
this.productAvailableUnit = productAvailableUnit;
}
public double getProductAvailableUnitTransportationCharge() {
return productAvailableUnitTransportationCharge;
}
public void setProductAvailableUnitTransportationCharge(double productAvailableUnitTransportationCharge) {
this.productAvailableUnitTransportationCharge = productAvailableUnitTransportationCharge;
}
public double getProductAvailableUnitLabourCharge() {
return productAvailableUnitLabourCharge;
}
public void setProductAvailableUnitLabourCharge(double productAvailableUnitLabourCharge) {
this.productAvailableUnitLabourCharge = productAvailableUnitLabourCharge;
}
public double getProductAvailableUnitOtherCharge() {
return productAvailableUnitOtherCharge;
}
public void setProductAvailableUnitOtherCharge(double productAvailableUnitOtherCharge) {
this.productAvailableUnitOtherCharge = productAvailableUnitOtherCharge;
}
public Lot getLot() {
return lot;
}
public void setLot(Lot lot) {
this.lot = lot;
}
}
I am using hibernate-validator4.1.0.Final and JSR 303 for validation.
As you can see that I have two model classes Lot and ProductAvailable with mapping OneToMany that means one Lot can have Many ProductAvailable.
My Problem is: My custom annotaion IsUnit working fine with class Lot but throwing exception in case of class ProductAvailable.
Exception is:
javax.validation.ConstraintViolationException: Validation failed for classes [com.rapidtech.rapidtechorganic.model.ProductAvailable] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Please Enter a valid UNIT e.g. kg,litre,ton', propertyPath=productAvailableUnit, rootBeanClass=class com.rapidtech.rapidtechorganic.model.ProductAvailable, messageTemplate='Please Enter a valid UNIT e.g. kg,litre,ton'}
]
org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:138)
org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:78)
org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:205)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:82)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
com.rapidtech.rapidtechorganic.dao.AbstractDao.save(AbstractDao.java:30)
com.rapidtech.rapidtechorganic.dao.lot.LotDaoImpl.save(LotDaoImpl.java:22)
com.rapidtech.rapidtechorganic.service.LotServiceImpl.save(LotServiceImpl.java:25)
com.rapidtech.rapidtechorganic.controller.LotController.saveLotController(LotController.java:59)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My Controller class looks like this:
#RequestMapping(value = "/saveLot", method = RequestMethod.POST)
public ModelAndView saveLotController(#Valid #ModelAttribute(value="lot") Lot lot, BindingResult result) {
ModelAndView model;
if(result.hasErrors()){
model = new ModelAndView("saveLotForm");
}
else {
Services lotService = (LotServiceImpl) appContext.getBean("lotServiceImpl");
lot.getProductAvailable().setLot(lot);
lotService.save(lot);
model = new ModelAndView("Success");
model.addObject("successMessage","Lot "+lot.getLotName()+" Saved Successfully!");
}
return model;
}
Any help would be appreaciated and Thanks in Advance.
Afte doing some research I have found the solution. All I need to put #Valid annotation over my productAvailable member variable of class Lot
Then it will check the validation for my ProductAvailable class.
How to Validate different model class into one form using Spring MVC JSR-303 Validator
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?
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.
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