How to get Stringify specific column value with many braces - ajax

I am new at java spring web mvc and im currently trying to create an ajax response using spring controller.
Here is my code:
Controller Class
#Controller
#RequestMapping("/")
public class AppController {
#Autowired
EmployeeService service;
#Autowired
MessageSource messageSource;
#RequestMapping(value = { "/editAjax-{ssn}-employee" }, method = RequestMethod.GET, produces = "application/json")
public #ResponseBody Employee check1(#PathVariable String ssn,
HttpServletRequest request, HttpServletResponse response) {
Employee employee = service.findEmployeeBySsn(ssn);
return employee;
}
}
Model Class
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Size(min = 3, max = 50)
#Column(name = "NAME", nullable = false)
private String name;
#Size(min = 5, max = 200)
#Column(name = "ADDRESS", nullable = false)
private String address;
#NotNull
#Digits(integer = 8, fraction = 2)
#Column(name="SALARY", nullable = false)
private BigDecimal salary;
#NotEmpty
#Column(name="SSN", unique = true, nullable = false)
private String ssn;
#NotNull
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "JOINING_DATE", nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", address=" + address
+ ", salary=" + salary + ", ssn=" + ssn + ", joiningDate="
+ joiningDate + "]";
}
// Empty Constructor
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
}
and here is my script inside jsp
<script>
/* This function provide response from controller retrieving employee
* detail via ssn id.
*/
function searchViaAjax(obj) {
var stringResponse;
var id = obj.id;
$.ajax({
/* Controller Request Mapping */
url : "${pageContext.request.contextPath}/editAjax-${'" + id
+ "'}-employee",
type : "GET",
contentType : "application/json",
dataType : "json",
success : function(response) {
/* Convert response into String */
stringResponse = JSON.stringify(response, [ 'id', 'name',
'address', 'salary', 'ssn', 'joiningDate' ]);
console.log(stringResponse);
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
</script>
console result:
sucess! {"id":6,"name":"test","address":"Makati city","salary":124565,"ssn":"2","joiningDate":{}}
As you can see i failed to get the joiningDate value.
When i access the web url directly the output of response is this. All works fine i get the value of id,name,address,salary,ssn,joiningDate.
But in joiningDate there are so many braces and fields i think because of the type in model class that set into org.jadira.usertype.dateandtime.joda.PersistentLocalDate? How can i get only atleast the "values":[2018,3,27] in joiningDate field?
Is there a way to retrieve the values that i want only despite in many values inside joiningDate? Do i need to change the type in my model class?
{"id":6,"name":"test","address":"Makati city","salary":124565,"ssn":"2","joiningDate":{"dayOfMonth":27,"dayOfWeek":2,"era":1,"year":2018,"dayOfYear":86,"chronology":{"zone":{"fixed":true,"id":"UTC"}},"weekyear":2018,"monthOfYear":3,"yearOfEra":2018,"yearOfCentury":18,"centuryOfEra":20,"weekOfWeekyear":13,"fields":[{"lenient":false,"maximumValue":292278993,"minimumValue":-292275054,"rangeDurationField":null,"leapDurationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"durationField":{"unitMillis":31556952000,"precise":false,"name":"years","type":{"name":"years"},"supported":true},"name":"year","type":{"durationType":{"name":"years"},"rangeDurationType":null,"name":"year"},"supported":true},{"lenient":false,"maximumValue":12,"minimumValue":1,"rangeDurationField":{"unitMillis":31556952000,"precise":false,"name":"years","type":{"name":"years"},"supported":true},"leapDurationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"durationField":{"unitMillis":2629746000,"precise":false,"name":"months","type":{"name":"months"},"supported":true},"name":"monthOfYear","type":{"durationType":{"name":"months"},"rangeDurationType":{"name":"years"},"name":"monthOfYear"},"supported":true},{"maximumValue":31,"minimumValue":1,"rangeDurationField":{"unitMillis":2629746000,"precise":false,"name":"months","type":{"name":"months"},"supported":true},"lenient":false,"unitMillis":86400000,"durationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"name":"dayOfMonth","type":{"durationType":{"name":"days"},"rangeDurationType":{"name":"months"},"name":"dayOfMonth"},"supported":true,"leapDurationField":null}],"values":[2018,3,27],"fieldTypes":[{"durationType":{"name":"years"},"rangeDurationType":null,"name":"year"},{"durationType":{"name":"months"},"rangeDurationType":{"name":"years"},"name":"monthOfYear"},{"durationType":{"name":"days"},"rangeDurationType":{"name":"months"},"name":"dayOfMonth"}]}}
UPDATE:
When i try to remove the #Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate") i got an error. it says could not deserialize.
Apr 05, 2018 12:50:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/MavenTry] threw exception [Request processing failed; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.StreamCorruptedException: invalid stream header: 32303138
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:354)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1695)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1627)
at org.hibernate.loader.Loader.getRow(Loader.java:1514)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:725)
at org.hibernate.loader.Loader.processResultSet(Loader.java:952)
at org.hibernate.loader.Loader.doQuery(Loader.java:920)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.websystique.springmvc.dao.EmployeeDaoImpl.findAllEmployee(EmployeeDaoImpl.java:44)
at com.websystique.springmvc.service.EmployeeServiceImpl.findAllEmployee(EmployeeServiceImpl.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy112.findAllEmployee(Unknown Source)
at com.websystique.springmvc.controller.AppController.employeeList(AppController.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
For The full code reference. This is the tutorial of this program. http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/

Related

Cassandra Spring No Converter Found Capable of Converting from Type Instant to type Long

Am getting a No converter found capable of converting from type Instant to type Long while using Spring and Cassandra.
I have 2 Instant fields writtenDate (in the object primary key) and hotelAddedDate in the object. However, I do not have any Long fields; thus, I am a little confused.
Does anyone have an idea how to fix this error?
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.Instant] to type [java.lang.Long]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:322)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175)
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.convertIfNecessary(ConvertingPropertyAccessor.java:120)
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.getProperty(ConvertingPropertyAccessor.java:91)
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.getWriteValue(MappingCassandraConverter.java:771)
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.writeInternal(MappingCassandraConverter.java:518)
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.writeInternal(MappingCassandraConverter.java:513)
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.write(MappingCassandraConverter.java:484)
at org.springframework.data.cassandra.core.StatementFactory.insert(StatementFactory.java:308)
at org.springframework.data.cassandra.core.CassandraTemplate.doInsert(CassandraTemplate.java:674)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:664)
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:96)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:639)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy199.save(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy199.save(Unknown Source)
at com.saathratri.tajvote.service.impl.CustomerReviewsByHotelAndLastNameAndFirstNameServiceImpl.save(CustomerReviewsByHotelAndLastNameAndFirstNameServiceImpl.java:36)
at com.saathratri.tajvote.service.impl.CustomerReviewsByHotelAndLastNameAndFirstNameServiceImpl$$FastClassBySpringCGLIB$$da12f07b.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)
at com.saathratri.tajvote.aop.logging.LoggingAspect.logAround(LoggingAspect.java:105)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:634)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:624)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:72)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
at com.saathratri.tajvote.service.impl.CustomerReviewsByHotelAndLastNameAndFirstNameServiceImpl$$EnhancerBySpringCGLIB$$eda9c521.save(<generated>)
at com.saathratri.tajvote.web.rest.CustomerReviewsByHotelAndLastNameAndFirstNameResource.createCustomerReviewsByHotelAndLastNameAndFirstName(CustomerReviewsByHotelAndLastNameAndFirstNameResource.java:77)
at com.saathratri.tajvote.web.rest.CustomerReviewsByHotelAndLastNameAndFirstNameResource$$FastClassBySpringCGLIB$$d91d43fd.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
...
Here is my CQL for creating the table in Cassandra:
create table customer_reviews_by_hotel_and_last_name_and_first_name (
hotel_id uuid,
last_name text,
first_name text,
written_date timestamp,
review_id timeuuid,
customer_id uuid,
customer_email_addresses set<text>,
customer_phone_numbers set<text>,
added_source text,
main_star_rating tinyint,
comments text,
enjoyed_stay boolean,
would_recommend boolean,
hotel_added_date timestamp,
hotel_name text,
hotel_email text,
hotel_phone_number text,
primary key((hotel_id), last_name, first_name, written_date, review_id))
with clustering order by (last_name desc, first_name desc, written_date desc, review_id asc);
This is my primary key class:
package com.saathratri.tajvote.domain;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
import org.springframework.data.cassandra.core.cql.PrimaryKeyType;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyClass;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn;
#PrimaryKeyClass
public class CustomerReviewsByHotelAndLastNameAndFirstNameId
implements java.io.Serializable {
#PrimaryKeyColumn(
name = "hotel_id",
ordinal = 0,
type = PrimaryKeyType.PARTITIONED
)
#CassandraType(type = CassandraType.Name.UUID)
private UUID hotelId;
#PrimaryKeyColumn(
name = "last_name",
ordinal = 1,
type = PrimaryKeyType.CLUSTERED
)
#CassandraType(type = CassandraType.Name.TEXT)
private String lastName;
#PrimaryKeyColumn(
name = "first_name",
ordinal = 2,
type = PrimaryKeyType.CLUSTERED
)
#CassandraType(type = CassandraType.Name.TEXT)
private String firstName;
#PrimaryKeyColumn(
name = "written_date",
ordinal = 3,
type = PrimaryKeyType.CLUSTERED
)
#CassandraType(type = CassandraType.Name.BIGINT)
private Instant writtenDate;
#PrimaryKeyColumn(
name = "review_id",
ordinal = 4,
type = PrimaryKeyType.CLUSTERED
)
#CassandraType(type = CassandraType.Name.UUID)
private UUID reviewId;
public CustomerReviewsByHotelAndLastNameAndFirstNameId() {}
public CustomerReviewsByHotelAndLastNameAndFirstNameId(
UUID hotelId,
String lastName,
String firstName,
Instant writtenDate,
UUID reviewId
) {
this.hotelId = hotelId;
this.lastName = lastName;
this.firstName = firstName;
this.writtenDate = writtenDate;
this.reviewId = reviewId;
}
public UUID getHotelId() {
return this.hotelId;
}
public void setHotelId(UUID hotelId) {
this.hotelId = hotelId;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Instant getWrittenDate() {
return this.writtenDate;
}
public void setWrittenDate(Instant writtenDate) {
this.writtenDate = writtenDate;
}
public UUID getReviewId() {
return this.reviewId;
}
public void setReviewId(UUID reviewId) {
this.reviewId = reviewId;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CustomerReviewsByHotelAndLastNameAndFirstNameId)) {
return false;
}
CustomerReviewsByHotelAndLastNameAndFirstNameId customerReviewsByHotelAndLastNameAndFirstNameId = (CustomerReviewsByHotelAndLastNameAndFirstNameId) o;
return (
Objects.equals(
hotelId,
customerReviewsByHotelAndLastNameAndFirstNameId.hotelId
) &&
Objects.equals(
lastName,
customerReviewsByHotelAndLastNameAndFirstNameId.lastName
) &&
Objects.equals(
firstName,
customerReviewsByHotelAndLastNameAndFirstNameId.firstName
) &&
Objects.equals(
writtenDate,
customerReviewsByHotelAndLastNameAndFirstNameId.writtenDate
) &&
Objects.equals(
reviewId,
customerReviewsByHotelAndLastNameAndFirstNameId.reviewId
)
);
}
#Override
public int hashCode() {
return Objects.hash(hotelId, lastName, firstName, writtenDate, reviewId);
}
// prettier-ignore
#Override
public String toString() {
return "CustomerReviewsByHotelAndLastNameAndFirstNameId{" +
", hotelId='" + getHotelId() + "'" +
", lastName='" + getLastName() + "'" +
", firstName='" + getFirstName() + "'" +
", writtenDate='" + getWrittenDate() + "'" +
", reviewId='" + getReviewId() + "'" +
"}";
}
}
This my domain class:
package com.saathratri.tajvote.domain;
import java.io.Serializable;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
/**
* A CustomerReviewsByHotelAndLastNameAndFirstName.
*/
#Table("customer_reviews_by_hotel_and_last_name_and_first_name")
public class CustomerReviewsByHotelAndLastNameAndFirstName
implements Serializable {
private static final long serialVersionUID = 1L;
#PrimaryKey
private CustomerReviewsByHotelAndLastNameAndFirstNameId id;
#Column("customer_id")
#CassandraType(type = CassandraType.Name.UUID)
private UUID customerId;
#Column("customer_email_addresses")
#CassandraType(
type = CassandraType.Name.SET,
typeArguments = CassandraType.Name.TEXT
)
private Set<String> customerEmailAddresses;
#Column("customer_phone_numbers")
#CassandraType(
type = CassandraType.Name.SET,
typeArguments = CassandraType.Name.TEXT
)
private Set<String> customerPhoneNumbers;
#Column("added_source")
#CassandraType(type = CassandraType.Name.TEXT)
private String addedSource;
#Column("main_star_rating")
#CassandraType(type = CassandraType.Name.TINYINT)
private Integer mainStarRating;
#Column("comments")
#CassandraType(type = CassandraType.Name.TEXT)
private String comments;
#Column("enjoyed_stay")
#CassandraType(type = CassandraType.Name.BOOLEAN)
private Boolean enjoyedStay;
#Column("would_recommend")
#CassandraType(type = CassandraType.Name.BOOLEAN)
private Boolean wouldRecommend;
#Column("hotel_added_date")
#CassandraType(type = CassandraType.Name.BIGINT)
private Instant hotelAddedDate;
#Column("hotel_name")
#CassandraType(type = CassandraType.Name.TEXT)
private String hotelName;
#Column("hotel_email")
#CassandraType(type = CassandraType.Name.TEXT)
private String hotelEmail;
#Column("hotel_phone_number")
#CassandraType(type = CassandraType.Name.TEXT)
private String hotelPhoneNumber;
public CustomerReviewsByHotelAndLastNameAndFirstNameId getId() {
return id;
}
public void setId(CustomerReviewsByHotelAndLastNameAndFirstNameId id) {
this.id = id;
}
public CustomerReviewsByHotelAndLastNameAndFirstName id(
CustomerReviewsByHotelAndLastNameAndFirstNameId id
) {
this.id = id;
return this;
}
// jhipster-needle-entity-add-field - JHipster will add fields here
public UUID getCustomerId() {
return this.customerId;
}
public CustomerReviewsByHotelAndLastNameAndFirstName customerId(
UUID customerId
) {
this.setCustomerId(customerId);
return this;
}
public void setCustomerId(UUID customerId) {
this.customerId = customerId;
}
public Set<String> getCustomerEmailAddresses() {
return this.customerEmailAddresses;
}
public CustomerReviewsByHotelAndLastNameAndFirstName customerEmailAddresses(
Set<String> customerEmailAddresses
) {
this.setCustomerEmailAddresses(customerEmailAddresses);
return this;
}
public void setCustomerEmailAddresses(Set<String> customerEmailAddresses) {
this.customerEmailAddresses = customerEmailAddresses;
}
public Set<String> getCustomerPhoneNumbers() {
return this.customerPhoneNumbers;
}
public CustomerReviewsByHotelAndLastNameAndFirstName customerPhoneNumbers(
Set<String> customerPhoneNumbers
) {
this.setCustomerPhoneNumbers(customerPhoneNumbers);
return this;
}
public void setCustomerPhoneNumbers(Set<String> customerPhoneNumbers) {
this.customerPhoneNumbers = customerPhoneNumbers;
}
public String getAddedSource() {
return this.addedSource;
}
public CustomerReviewsByHotelAndLastNameAndFirstName addedSource(
String addedSource
) {
this.setAddedSource(addedSource);
return this;
}
public void setAddedSource(String addedSource) {
this.addedSource = addedSource;
}
public Integer getMainStarRating() {
return this.mainStarRating;
}
public CustomerReviewsByHotelAndLastNameAndFirstName mainStarRating(
Integer mainStarRating
) {
this.setMainStarRating(mainStarRating);
return this;
}
public void setMainStarRating(Integer mainStarRating) {
this.mainStarRating = mainStarRating;
}
public String getComments() {
return this.comments;
}
public CustomerReviewsByHotelAndLastNameAndFirstName comments(
String comments
) {
this.setComments(comments);
return this;
}
public void setComments(String comments) {
this.comments = comments;
}
public Boolean getEnjoyedStay() {
return this.enjoyedStay;
}
public CustomerReviewsByHotelAndLastNameAndFirstName enjoyedStay(
Boolean enjoyedStay
) {
this.setEnjoyedStay(enjoyedStay);
return this;
}
public void setEnjoyedStay(Boolean enjoyedStay) {
this.enjoyedStay = enjoyedStay;
}
public Boolean getWouldRecommend() {
return this.wouldRecommend;
}
public CustomerReviewsByHotelAndLastNameAndFirstName wouldRecommend(
Boolean wouldRecommend
) {
this.setWouldRecommend(wouldRecommend);
return this;
}
public void setWouldRecommend(Boolean wouldRecommend) {
this.wouldRecommend = wouldRecommend;
}
public Instant getHotelAddedDate() {
return this.hotelAddedDate;
}
public CustomerReviewsByHotelAndLastNameAndFirstName hotelAddedDate(
Instant hotelAddedDate
) {
this.setHotelAddedDate(hotelAddedDate);
return this;
}
public void setHotelAddedDate(Instant hotelAddedDate) {
this.hotelAddedDate = hotelAddedDate;
}
public String getHotelName() {
return this.hotelName;
}
public CustomerReviewsByHotelAndLastNameAndFirstName hotelName(
String hotelName
) {
this.setHotelName(hotelName);
return this;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public String getHotelEmail() {
return this.hotelEmail;
}
public CustomerReviewsByHotelAndLastNameAndFirstName hotelEmail(
String hotelEmail
) {
this.setHotelEmail(hotelEmail);
return this;
}
public void setHotelEmail(String hotelEmail) {
this.hotelEmail = hotelEmail;
}
public String getHotelPhoneNumber() {
return this.hotelPhoneNumber;
}
public CustomerReviewsByHotelAndLastNameAndFirstName hotelPhoneNumber(
String hotelPhoneNumber
) {
this.setHotelPhoneNumber(hotelPhoneNumber);
return this;
}
public void setHotelPhoneNumber(String hotelPhoneNumber) {
this.hotelPhoneNumber = hotelPhoneNumber;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CustomerReviewsByHotelAndLastNameAndFirstName)) {
return false;
}
return (
id != null &&
id.equals(((CustomerReviewsByHotelAndLastNameAndFirstName) o).id)
);
}
#Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
#Override
public String toString() {
return "CustomerReviewsByHotelAndLastNameAndFirstName{" +
"id=" + getId() +
", customerId='" + getCustomerId() + "'" +
", customerEmailAddresses='" + getCustomerEmailAddresses() + "'" +
", customerPhoneNumbers='" + getCustomerPhoneNumbers() + "'" +
", addedSource='" + getAddedSource() + "'" +
", mainStarRating=" + getMainStarRating() +
", comments='" + getComments() + "'" +
", enjoyedStay='" + getEnjoyedStay() + "'" +
", wouldRecommend='" + getWouldRecommend() + "'" +
", hotelAddedDate='" + getHotelAddedDate() + "'" +
", hotelName='" + getHotelName() + "'" +
", hotelEmail='" + getHotelEmail() + "'" +
", hotelPhoneNumber='" + getHotelPhoneNumber() + "'" +
"}";
}
}
Had to change CassandraType.Name.BIGINT to CassandraType.Name.TIMESTAMP:
In CustomerReviewsByHotelAndLastNameAndFirstName.java:
...
#Column("hotel_added_date")
#CassandraType(type = CassandraType.Name.TIMESTAMP)
private Instant hotelAddedDate;
...
In CustomerReviewsByHotelAndLastNameAndFirstNameId.java:
...
#PrimaryKeyColumn(
name = "written_date",
ordinal = 3,
type = PrimaryKeyType.CLUSTERED
)
#CassandraType(type = CassandraType.Name.TIMESTAMP)
private Instant writtenDate;
...

How to resolve this error TransactionException: commit failed?

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

Not-null property references a transient value - transient instance must be saved before current operation

This is the log exception:
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/Libreria] threw exception [Request processing failed; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.angelo.springmvc.model.PrestitoLibro.prestito -> com.angelo.springmvc.model.Prestito] with root cause
org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.angelo.springmvc.model.PrestitoLibro.prestito -> com.angelo.springmvc.model.Prestito
at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation(UnresolvedEntityInsertActions.java:137)
at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation(ActionQueue.java:318)
at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation(SessionImpl.java:658)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:813)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at com.angelo.springmvc.dao.AbstractDao.persist(AbstractDao.java:34)
at com.angelo.springmvc.dao.PrestitoLibroDaoImpl.savePrestitoLibro(PrestitoLibroDaoImpl.java:27)
at com.angelo.springmvc.service.PrestitoServiceImpl.salvaPrestito(PrestitoServiceImpl.java:85)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy45.salvaPrestito(Unknown Source)
at com.angelo.springmvc.controller.ShoppingCartController.ordinaShoppingCart(ShoppingCartController.java:62)
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.invoke(InvocableHandlerMethod.java:215)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
The scenario is the following: I have two entity beans Prestito and PrestitoLibro, a ServicePrestito and a session bean ShoppingCard with a Controller:
#Entity
#Table(name="PRESTITO")
#XmlRootElement
public class Prestito {
private Integer id;
private Cliente cliente;
private Date dataprestito;
private Set<PrestitoLibro> prestitolibros = new HashSet<PrestitoLibro>(0);
public Prestito() {
}
public Prestito(Cliente cliente, Date dataprestito) {
this.cliente = cliente;
this.dataprestito = dataprestito;
}
public Prestito(Cliente cliente, Date dataprestito, Set<PrestitoLibro> prestitolibros) {
this.cliente = cliente;
this.dataprestito = dataprestito;
this.prestitolibros = prestitolibros;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_cliente", nullable = false)
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
#Temporal(TemporalType.DATE)
#Column(name = "dataprestito", nullable = false, length = 10)
public Date getDataprestito() {
return this.dataprestito;
}
public void setDataprestito(Date dataprestito) {
this.dataprestito = dataprestito;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "prestito")
public Set<PrestitoLibro> getPrestitolibros() {
return this.prestitolibros;
}
public void setPrestitolibros(Set<PrestitoLibro> prestitolibros) {
this.prestitolibros = prestitolibros;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Prestito other = (Prestito) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
#Override
public String toString() {
return "Prestito [id=" + id + ", cliente=" + cliente + ", dataprestito=" + dataprestito
+ ", prestitolibros=" + prestitolibros + "]";
}
}
#Entity
#Table(name="PRESTITOLIBRO")
#XmlRootElement
public class PrestitoLibro {
private Integer id;
private Libro libro;
private Prestito prestito;
private Integer qta;
private Double subtotal;
public PrestitoLibro() {
}
public PrestitoLibro(Libro libro, Prestito prestito) {
this.libro = libro;
this.prestito = prestito;
}
public PrestitoLibro(Libro libro, Prestito prestito, Integer qta, Double subtotal) {
this.libro = libro;
this.prestito = prestito;
this.qta = qta;
this.subtotal = subtotal;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)//, cascade=CascadeType.ALL
#JoinColumn(name = "id_libro", nullable = false)
public Libro getLibro() {
return this.libro;
}
public void setLibro(Libro libro) {
this.libro = libro;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_prestito", nullable = false)
public Prestito getPrestito() {
return this.prestito;
}
public void setPrestito(Prestito prestito) {
this.prestito = prestito;
}
#Column(name = "qta")
public Integer getQta() {
return this.qta;
}
public void setQta(Integer qta) {
this.qta = qta;
}
#Column(name = "subtotal", precision = 22, scale = 0)
public Double getSubtotal() {
return this.subtotal;
}
public void setSubtotal(Double subtotal) {
this.subtotal = subtotal;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrestitoLibro other = (PrestitoLibro) obj;
if (id != other.id)
return false;
return true;
}
#Override
public String toString() {
return "PrestitoLibro [id=" + id + ", libro=" + libro + ", prestito=" + prestito + ", qta=" + qta
+ ", subtotal=" + subtotal + "]";
}
}
#Component
#Scope(value=WebApplicationContext.SCOPE_SESSION,
proxyMode=ScopedProxyMode.TARGET_CLASS)
public class ShoppingCart {
private Map<Libro, Integer> contents = new HashMap<>();
public Map<Libro, Integer> getContents() {
return contents;
}
public void setContents(Map<Libro, Integer> contents) {
this.contents = contents;
}
public void addLibro(Libro libro, int count){
if(contents.containsKey(libro)){
contents.put(libro, contents.get(libro)+count);
}else{
contents.put(libro,count);
}
}
public void removeLibro(Libro libro){
contents.remove(libro);
}
public void clearCart(){
contents.clear();
}
#Override
public String toString() {
return "ShoppingCart [contents=" + contents + "]";
}
public double getTotalCost(){
double totalcost = 0;
int i = 0;
for(Libro libro: contents.keySet()){
i = contents.get(libro);
totalcost += i * libro.getPrezzo();
}
return totalcost;
}
}
The problem occurs when I call salvaprestito() here:
#Service("prestitoService")
#Transactional
public class PrestitoServiceImpl implements PrestitoService {
#Autowired
private PrestitoDao dao;
#Autowired
private PrestitoLibroDao daoprestitolibro;
public Prestito findById(int id) {
return dao.findById(id);
}
public void savePrestito(Prestito prestito) {
dao.savePrestito(prestito);
}
public void updatePrestito(Prestito prestito) {
Prestito entity = dao.findById(prestito.getId());
if(entity!=null){
entity.setCliente(prestito.getCliente());
entity.setDataprestito(prestito.getDataprestito());
entity.setPrestitolibros(prestito.getPrestitolibros());
}
}
public void deletePrestitoBySss(String sss) {
dao.deletePrestitoBySss(sss);
}
public List<Prestito> findAllPrestiti() {
return dao.findAllPrestiti();
}
public Prestito findPrestitoBySss(String sss) {
return dao.findPrestitoBySss(sss);
}
public boolean isPrestitoSssUnique(Integer id, String sss) {
Prestito prestito = findPrestitoBySss(sss);
return ( prestito == null || ((id != null) && (prestito.getId() == id)));
}
public void salvaPrestito(Map<Libro, Integer> shoppingcartContents, Cliente cliente){
Prestito prestito = new Prestito();
prestito = dao.findById(prestito.getId());
prestito.setCliente(cliente);
dao.savePrestito(prestito);
for(Entry<Libro, Integer> entry: shoppingcartContents.entrySet()){
PrestitoLibro prestLibro = new PrestitoLibro(entry.getKey(),prestito);
prestLibro.setQta(entry.getValue());
prestLibro.setPrestito(prestito); prestLibro.setSubtotal(entry.getKey().getPrezzo()*entry.getValue());
daoprestitolibro.savePrestitoLibro(prestLibro);
prestito.getPrestitolibros().add(prestLibro);
}
}
And this is the Shopping Cart Controller:
#Controller
public class ShoppingCartController {
private static final Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);
#Autowired
private LibroService libroservice;
#Autowired
private PrestitoService prestitoservice;
#Autowired
private ShoppingCart shoppingcart;
#RequestMapping(value = { "/shoppingcart/add/{libroId}" }, method = RequestMethod.GET)
public String addtoShoppingCart(#PathVariable("libroId") int libroId, #RequestHeader("referer") String rForm) {
Libro libro = (Libro) libroservice.findById(libroId);
shoppingcart.addLibro(libro, 1);
logger.debug("Aggiunto Libro a carrello" + libro);
return "redirect:" + rForm;
}
#RequestMapping(value = { "/shoppingcart" }, method = RequestMethod.GET)
public String viewShoppingCart(Model model) {
model.addAttribute("shoppingcart", shoppingcart);
return "shoppingcart";
}
#RequestMapping(value = { "/shoppingcart/order" }, method = RequestMethod.POST)
public String ordinaShoppingCart(HttpSession session) {
if(shoppingcart.getContents().isEmpty()){
return "redirect:/shoppingcart";
}else{
Cliente cliente = (Cliente) session.getAttribute("cliente");
prestitoservice.salvaPrestito(shoppingcart.getContents(), cliente);
return "redirect:/shoppingcart";
}
}
These are the Daos:
#Repository("prestitolibroDao")
public class PrestitoLibroDaoImpl extends AbstractDao<Integer, PrestitoLibro> implements PrestitoLibroDao{
public PrestitoLibro findById(int id) {
PrestitoLibro prestitolibro = getByKey(id);
if(prestitolibro!=null){
Hibernate.initialize(prestitolibro.getId());
}
return prestitolibro;
}
public void savePrestitoLibro(PrestitoLibro prestitolibro) {
persist(prestitolibro);
}
public void deletePrestitoLibroById(int id) {
Query query = getSession().createSQLQuery("delete from Prestitolibro where id = :id");
query.setString("id",(String) Integer.toString(id));
query.executeUpdate();
}
#SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibro() {
Criteria criteria = createEntityCriteria();
return (List<PrestitoLibro>) criteria.list();
}
#SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibroByPrestito(int prestitoId) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("id_prestito", prestitoId));
return (List<PrestitoLibro>) criteria.list();
}
#SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibroByLibro(int libroId) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("id_libro", libroId));
return (List<PrestitoLibro>) criteria.list();
}
#Repository("prestitoDao")
public class PrestitoDaoImpl extends AbstractDao<Integer, Prestito> implements PrestitoDao{
public Prestito findById(int id) {
Prestito prestito = getByKey(id);
if(prestito!=null){
Hibernate.initialize(prestito.getId());
}
return prestito;
}
public void savePrestito(Prestito prestito) {
persist(prestito);
// Save prestito significa salvare il prestito o/e anche PrestitoLibiri
}
public void deletePrestitoBySss(String sss) {
Query query = getSession().createSQLQuery("delete from Libro where snn = :snn");
query.setString("sss", sss);
query.executeUpdate();
}
#SuppressWarnings("unchecked")
public List<Prestito> findAllPrestiti() {
Criteria criteria = createEntityCriteria();
return (List<Prestito>) criteria.list();
}
public Prestito findPrestitoBySss(String sss) {
System.out.println("SSS : "+sss);
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("sss", sss));
Prestito prestito = (Prestito)criteria.uniqueResult();
if(prestito!=null){
Hibernate.initialize(prestito.getId());
}
return prestito;
}
Hibernate needs only id in Prestito to associate it with PrestitoLibro by a foreign key. I think, you don't have id in prestito here
prestLibro.setPrestito(prestito);
daoprestitolibro.savePrestitoLibro(prestLibro);
Try to output prestito.getId() before set it to prestLibro.
If you really don't have id the reason may be with this generation strategy
#GeneratedValue(strategy = IDENTITY)
or you don't have a transaction with #Transactional in the PrestitoServiceImpl so dao.savePrestito(prestito) doesn't save prestito at all. May be adding of your spring xml configuration in your question let to help you.
You do some unnecessary stuff in your method so it should be
public void salvaPrestito(Map<Libro, Integer> shoppingcartContents, Cliente cliente){
Prestito prestito = new Prestito();
prestito.setCliente(cliente);
dao.savePrestito(prestito);
for(Entry<Libro, Integer> entry: shoppingcartContents.entrySet()){
PrestitoLibro prestLibro = new PrestitoLibro(entry.getKey(), prestito);
prestLibro.setQta(entry.getValue());
prestLibro.setSubtotal(entry.getKey().getPrezzo() * entry.getValue());
daoprestitolibro.savePrestitoLibro(prestLibro);
}
}
You don't need prestLibro.setPrestito(prestito) and
prestito.getPrestitolibros().add(prestLibro).

failed to lazily initialize a collection

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

Spring REST Controller Test with spring-test-mvc framework

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

Resources