Spring Hibernate annotation based master details data save error - spring

I am new to Spring framework. I am trying to insert a department with some personnel in database. I am using spring-mvc and Hibernate to do so. I am following this article to implement, but I am not creating the table by SQL. The table are creating on application runtime. I am using PostgreSQL. Here are my attempts below.
My department entity class:
#SuppressWarnings("deprecation")
#Entity
#Table(name="department")
public class Department {
#Id
#GeneratedValue
#Column(name="department_id")
private Long departmentId;
#Column(name="department_name")
private String departmentName;
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="department_id")
#IndexColumn(name="idx")
private List<Personnel> personnels;
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public List<Personnel> getPersonnels() {
return personnels;
}
public void setPersonnels(List<Personnel> personnels) {
this.personnels = personnels;
}
My personnel entity class:
#Entity
#Table(name="personnel")
public class Personnel {
#Id
#GeneratedValue
#Column(name="personnel_id")
private Long personnelId;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="birth_date")
private Date birthDate;
#Column(name="cell_phone")
private String cellphone;
#ManyToOne
#JoinColumn(name="department_id",
insertable=false, updatable=false,
nullable=false)
private Department department;
#Column(name="idx")
private Integer idx;
public Personnel() {
}
public Personnel(String firstname, String lastname, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = new Date(System.currentTimeMillis());
this.cellphone = phone;
}
}
My controller save action:
#RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String save(HttpServletRequest request) {
Map<String, String[]> department = request.getParameterMap();
Map<String, String> data = departmentService.insert(department);
System.out.println("######### >> Data Saved with id :: " + data.get("id"));
return "redirect:/department/show/" + data.get("id");
}
My service insert action:
public Map<String, String> insert(Map<String, String[]> map) {
Map<String, String> params = new HashMap<String, String>();
Long id = null;
Department department = new Department();
department.setDepartmentName(map.get("departmentName")[0]);
department.setPersonnels(new ArrayList<Personnel>());
Personnel emp1 = new Personnel("Nina", "Mayers", "111");
Personnel emp2 = new Personnel("Tony", "Almeida", "222");
department.getPersonnels().add(emp1);
department.getPersonnels().add(emp2);
id = departmentDao.insertDoc(department);
params.put("id", id.toString());
return params ;
}
My dao insertDoc action:
#Transactional
public Long insertDoc(Department doc) {
Long id = (Long) sessionfactory.getCurrentSession().save(doc);
sessionfactory.getCurrentSession().flush();
return id;
}
And finally the error I get:
SEVERE: Servlet.service() for servlet [testSpring] in context with path [/testSpring] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "department_id" violates not-null constraint
Detail: Failing row contains (16, 2016-08-27, 111, Nina, null, Mayers, null).
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.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2921)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3421)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
at com.stock.dao.DepartmentDao.insertDoc(DepartmentDao.java:23)
at com.stock.dao.DepartmentDao$$FastClassBySpringCGLIB$$132caf1f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.stock.dao.DepartmentDao$$EnhancerBySpringCGLIB$$36cc6e45.insertDoc(<generated>)
at com.stock.service.DepartmentService.insert(DepartmentService.java:34)
at com.stock.controller.DepartmentController.save(DepartmentController.java:36)
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.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
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:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
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(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
It is showing null value problem in department_id. How can I solve it with this code block?

you also need to set department in Personnel also rest of the thing will be take care by hibernate .:
eg :
public Map<String, String> insert(Map<String, String[]> map) {
Map<String, String> params = new HashMap<String, String>();
Long id = null;
Department department = new Department();
department.setDepartmentName(map.get("departmentName")[0]);
department.setPersonnels(new ArrayList<Personnel>());
Personnel emp1 = new Personnel("Nina", "Mayers", "111");
Personnel emp2 = new Personnel("Tony", "Almeida", "222");
// Set Department in your emp1 and emp2 object
emp1.setDepartment(department);
emp2.setDepartment(department);
department.getPersonnels().add(emp1);
department.getPersonnels().add(emp2);
id = departmentDao.insertDoc(department);
params.put("id", id.toString());
return params ;
}
change log :
// Set Department in your emp1 and emp2 object
emp1.setDepartment(department);
emp2.setDepartment(department);

Read the error message carefully:
ERROR: null value in column "department_id" violates not-null constraint
Your department_id column in the department table has a non null constraint, which is being violated when you try to insert the following entity using Hibernate:
Department department = new Department();
department.setDepartmentName(map.get("departmentName")[0]);
department.setPersonnels(new ArrayList<Personnel>());
You never assign the ID, which is defaulting to NULL, causing the error you are seeing. To remedy this, assign a non null ID to the department before inserting:
department.setDepartmentId(1L); // or any value you wish

Related

PersistentObjectException: Uninitialized proxy passed to persist

I am working with Spring Data JPA and an MySQL database for a records management system. Below are two entities that I have modeled and I am trying to persist a Policy record to the database:
Policy Entity:
public class Policy {
private String policyNumber;
private String policyName;
private Steward steward;
private PolicyHolder policyHolder;
#Id
#Column(length = 30)
public String getPolicyNumber() {
return policyNumber;
}
public void setPolicyNumber(String policyNumber) {
this.policyNumber = policyNumber;
}
#Column(length = 80)
public String getPolicyName() {
return policyName;
}
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
#OneToOne(cascade = ALL, mappedBy = "policy", orphanRemoval = true, optional = false)
public PolicyHolder getPolicyHolder() {
return policyHolder;
}
}
PolicyHolder Entity:
#Entity
public class PolicyHolder extends PolicyMember {
private Policy policy;
public PolicyHolder() {
super();
}
#OneToOne
#JoinColumn(name = "policy_policyNumber", referencedColumnName = "policyNumber")
public Policy getPolicy() {
return policy;
}
public void setPolicy(Policy policy) {
this.policy = policy;
}
#Override
public String toString() {
return "PolicyHolder{" +
"policy=" + policy +
"} " + super.toString();
}
}
PolicyMember Entity:
#Entity
public abstract class PolicyMember {
private CompositePolicyMemberPK policyMemberId;
private String firstname;
private String surname;
private LocalDate dateOfDeath;
private LocalDate dateOfBirth;
private MemberStatus status;
private BillingStatus billingStatus;
private String nationalId;
private LocalDateTime creationDate;
private Gender gender;
private String msisdn;
private LocalDate closureDate;
private String createdBy;
private String memberType;
private PackageBenefit packageBenefit;
private List<DependantTransferRequest> transferRequests;
#EmbeddedId
public CompositePolicyMemberPK getPolicyMemberId() {
return policyMemberId;
}
public void setPolicyMemberId(CompositePolicyMemberPK policyMemberId) {
this.policyMemberId = policyMemberId;
}
#Column(length = 50)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(length = 50)
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Convert(converter = MemberStatusConverter.class)
public MemberStatus getStatus() {
return status;
}
public void setStatus(MemberStatus status) {
this.status = status;
}
#Convert(converter = BillingStatusConverter.class)
public BillingStatus getBillingStatus() {
return billingStatus;
}
public void setBillingStatus(BillingStatus billingStatus) {
this.billingStatus = billingStatus;
}
#Column(length = 20)
public String getNationalId() {
return nationalId;
}
public void setNationalId(String nationalId) {
this.nationalId = nationalId;
}
#Enumerated(EnumType.STRING)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
#Column(length = 15)
public String getMsisdn() {
return msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
#Column(length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "memberType", insertable = false, updatable = false)
public String getMemberType() {
return memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
#OneToOne(mappedBy = "policyMember", optional = false, cascade = CascadeType.ALL)
public PackageBenefit getPackageBenefit() {
return packageBenefit;
}
public void setPackageBenefit(PackageBenefit packageBenefit) {
this.packageBenefit = packageBenefit;
}
public LocalDate getDateOfDeath() {
return dateOfDeath;
}
public void setDateOfDeath(LocalDate dateOfDeath) {
this.dateOfDeath = dateOfDeath;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public LocalDate getClosureDate() {
return closureDate;
}
public void setClosureDate(LocalDate closureDate) {
this.closureDate = closureDate;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
#OneToMany(orphanRemoval = true, mappedBy = "dependantToTransfer")
public List<DependantTransferRequest> getTransferRequests() {
return transferRequests;
}
public void setTransferRequests(List<DependantTransferRequest> transferRequests) {
this.transferRequests = transferRequests;
}
}
Composite Key:
#Embeddable
public class CompositePolicyMemberPK implements Serializable {
private String policyNumber;
private String suffixNumber;
private static final long serialVersionUID = 1L;
public CompositePolicyMemberPK(String policyNumber, String suffixNumber) {
super();
this.policyNumber = policyNumber;
this.suffixNumber = suffixNumber;
}
public CompositePolicyMemberPK() {
super();
}
#Column(length = 30)
public String getPolicyNumber() {
return this.policyNumber;
}
public void setPolicyNumber(String policyNumber) {
this.policyNumber = policyNumber;
}
#Column(length = 2)
public String getSuffixNumber() {
return this.suffixNumber;
}
public void setSuffixNumber(String suffixNumber) {
this.suffixNumber = suffixNumber;
}
#Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof CompositePolicyMemberPK)) {
return false;
}
CompositePolicyMemberPK other = (CompositePolicyMemberPK) o;
return (getPolicyNumber() == null ? other.getPolicyNumber() == null : getPolicyNumber().equals(other.getPolicyNumber())) && (getSuffixNumber() == null ? other.getSuffixNumber() == null : getSuffixNumber().equals(other.getSuffixNumber()));
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (getPolicyNumber() == null ? 0 : getPolicyNumber().hashCode());
result = prime * result + (getSuffixNumber() == null ? 0 : getSuffixNumber().hashCode());
return result;
}
#Override
public String toString() {
return this.getPolicyNumber() + "-" + this.getSuffixNumber();
}
}
The code that is responsible for persisiting the policy is as follows:
public Subscriber addMemberToSteward(Long stewardId, Subscriber subscriber) {
Steward steward = this.findStewardById(stewardId);
if(steward == null){
throw new EcosureException(String.format("No steward found with id '%s'.",stewardId));
}
final BillingStatus billingStatus = BillingStatus.REG_IN_PROGRESS;
final MemberStatus memberStatus = MemberStatus.NEW;
final ProductPackage product = productService.findPackageById(subscriber.getProductPackageId());
subscriber.setNationalId(nationalIDNumberUtils.formatIdNumber(subscriber.getNationalId()));
final PolicyHolder policyHolder = convertToPolicyHolder(subscriber, product, billingStatus, memberStatus);
Policy policy = getPolicyFromSubscriberInfo(subscriber, policyHolder);
policy.setSteward(steward);
policy.setStatus(PolicyStatus.NEW);
System.out.println("Policy Holder" + policyHolder);
policyRepository.save(policy);
return subscriber;
}
The getPolicyFromSubscriberInfo method is below:
private Policy getPolicyFromSubscriberInfo(final Subscriber subscriberInfo, final PolicyHolder policyHolder) throws {
final Policy policy = new Policy();
policy.setMsisdn(subscriberInfo.getMsisdn());
policy.setPolicyNumber(policyNumberGenerator.getNextPolicyNumber());
policy.setPolicyName(policyHolder.getFirstname() + " " + policyHolder.getSurname());
policyHolder.setPolicy(policy);
CompositePolicyMemberPK policyMemberId = new CompositePolicyMemberPK();
policyMemberId.setPolicyNumber(policy.getPolicyNumber());
policyMemberId.setSuffixNumber(policyNumberGenerator.getNextSuffix(policy.getPolicyNumber(),true));
policyHolder.setPolicyMemberId(policyMemberId);
policy.setPolicyHolder(policyHolder);
return policy;
}
The PolicyRepository is shown below:
public interface PolicyRepository extends JpaRepository<Policy, String> {
}
When I try to persist a Policy entity I am getting the error below:
2016-12-09 09:47:43,461 ERROR [io.undertow.request] (default task-15) UT005023: Exception handling request to /ecosure-api/api/v3/stewards/243/policies: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist(); nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at com.econetwireless.ecosure.api.filters.AuthenticationTokenFilter.doFilter(AuthenticationTokenFilter.java:60)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist(); nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:492)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy1272.save(Unknown Source)
at com.econetwireless.ecosure.service.stewards.StewardServiceImpl.addMemberToSteward(StewardServiceImpl.java:115)
at com.econetwireless.ecosure.api.controllers.StewardController.addMemberToGroup(StewardController.java:91)
at com.econetwireless.ecosure.api.controllers.StewardController$$FastClassBySpringCGLIB$$69e389b2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.econetwireless.ecosure.api.controllers.StewardController$$EnhancerBySpringCGLIB$$2d501d51.addMemberToGroup(<generated>)
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:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 65 more
Caused by: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1152)
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:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
at com.sun.proxy.$Proxy1267.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:506)
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:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 95 more
Caused by: org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:80)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:768)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:761)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:391)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:316)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:104)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:414)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:252)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:778)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:751)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:756)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
Can anyone please assist me in identifying where I am going wrong.

Could not execute JDBC batch update;

hi i am running spring with jpa application while i am inserting the data into data i am getting the above exception in my entity class i make the userid as generator value and in my database table column i given the userid as first column but while executing the query it is showing the userid column as last column can any one tell me why it is happening like this and why i am getting this exception.
here is my entity class
#Entity
#Table(name="user",schema="schm_mail")
public class UserEntity {
#Id
#SequenceGenerator(name = "generator", sequenceName = "schm_mail.userlogin_sequence", allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator" )
#Column(name="userid")
private int userId;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
#Column(name="mailid")
private String mailId;
#Column(name="phonenumber")
private String phoneNumber;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
here is my exception stack trace
java.sql.BatchUpdateException: Batch entry 0 insert into schm_mail.user (firstname, lastname, mailid, phonenumber, userid) values ('suresh', 'abc', 'abc#gmail.com', '1234567890', '5') was aborted. Call getNextException to see the cause.
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2619)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2752)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:513)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy19.persist(Unknown Source)
at com.mail.service.UserServiceImpl.persist(UserServiceImpl.java:17)
at com.mail.controller.HomeController.userLoginPost(HomeController.java:40)
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: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:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
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:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
user is reserved keyword in postgreSql so you need to change your table name to something which is not reserved keyword
http://www.postgresql.org/docs/8.3/static/sql-keywords-appendix.html

Spring Data missing property error when initialising the SOLR repository

I'm relatively new to spring. I'm trying to set up the spring-data-solr package. I'm using this customer class for both the JPA persistence with hibernate, and for writing to SOLR via the SOLR Data adapter. It hasn't worked yet.
When I start the server I get this error in the log:
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed;
nested exception is org.springframework.data.mapping.PropertyReferenceException: No property flush found for type Customer!
Originally, it was saying no property "save" found on customer, so I did a test and just added a property called save. Then if I add flush, it says no property "delete" found. But it doesn't seem right to just keep adding these properties onto my domain class. I seem to be missing something on this Customer class to support the SOLR repository (maybe).
Also if I disable the #EnableSOLRRepositories annotation on my configuration class, the error doesn't happen, so it's definitely a problem related to the SOLR repository configuration.
Does anyone have any idea what the problem might be?
The class is below:
package com.ideafactory.mvc.customers.model;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
#Entity(name = "customer")
#Table(name = "customers")
public class Customer implements UserDetails {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Basic
#Column(nullable = false)
private String preferredName;
#Basic
#Column(nullable = false)
private String firstName;
#Basic
#NotEmpty
private String lastName;
#Basic
#Column(unique = true)
#NotEmpty
#Email
private String email;
#Basic
#Column(nullable = false)
private String password;
#Basic
#Column(nullable = true)
private Date dateOfBirth;
#Basic
#Column(nullable = true)
private String bio;
#Basic
#Column(nullable = true)
private String website;
#Basic
#Column(nullable = true)
private Date lastLogin;
#Basic
#Column(nullable = true)
private Date lastLogout;
#Enumerated(EnumType.STRING)
private CustomerStatus status;
#Basic
#Column(nullable = false)
private Date createdAt;
#Basic
#Column(nullable = false)
private Date lastModified;
#Type(type = "org.hibernate.type.NumericBooleanType")
private boolean requiresReset;
#Type(type="org.hibernate.type.NumericBooleanType")
private boolean subscriber;
#Enumerated(EnumType.STRING)
private Gender gender;
#Basic
private String phoneNumber;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
private List<Address> addressBook;
public String getPreferredName() {
return preferredName;
}
public void setPreferredName(String preferredName) {
this.preferredName = preferredName;
}
public boolean isSubscriber() {
return subscriber;
}
public void setSubscriber(boolean subscriber) {
this.subscriber = subscriber;
}
public boolean isRequiresReset() {
return requiresReset;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public boolean getRequiresReset() {
return requiresReset;
}
public void setRequiresReset(boolean requiresReset) {
this.requiresReset = requiresReset;
}
#ManyToMany
#JoinTable(
name="customer_roles",
joinColumns={#JoinColumn(name="customerId", referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="roleId", referencedColumnName="id")})
private List<Role> roles;
#Transient
public boolean isPersisted() {
return (this.id != null);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password)
{
this.password = password;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
List<Role> userRoles = this.getRoles();
if(userRoles != null)
{
for (Role role : userRoles) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
authorities.add(authority);
}
}
return authorities;
}
#Override
public String getUsername()
{
return getEmail();
}
#Override
public String getPassword()
{
return this.password;
}
#Override
public boolean isAccountNonExpired()
{
return true;
}
#Override
public boolean isAccountNonLocked()
{
return true;
}
#Override
public boolean isCredentialsNonExpired()
{
return true;
}
#Override
public boolean isEnabled()
{
return true;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
#PrePersist
void createdAt() {
this.createdAt = this.lastModified = new Date();
}
#PreUpdate
void updatedAt() {
this.createdAt = new Date();
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Date getLastLogout() {
return lastLogout;
}
public void setLastLogout(Date lastLogout) {
this.lastLogout = lastLogout;
}
public CustomerStatus getStatus() {
return status;
}
public void setStatus(CustomerStatus status) {
this.status = status;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Address> getAddressBook() {
return addressBook;
}
public void setAddressBook(List<Address> addressBook) {
this.addressBook = addressBook;
}
}
This was all I had for the eCustomer Repository. Am I supposed to implement an extension class?
package com.ideafactory.mvc.customers.model;
import org.springframework.data.solr.repository.SolrCrudRepository;
/**
* This is the SOLR repository handler
*/
public interface CustomerSolrCrudRepositoryImpl extends SolrCrudRepository<Customer, String> {
}
************ Update Below ***************
I've narrowed the problem down a little. I downloaded the source code for the spring jpa and stuck a debug point on the SolrRepositoryFactory class. So this is bizarre, but it's trying to resolve the named queries from my hibernate JPA repository using SOLR. So at the point the exception happens, it's trying to initialise what looks like a named query against SOLR. In my CustomerRepository (the Hibernate one) I've got findByEmail(String email).
What am I missing here? Why would the Solr repository initialisation be doing anything with my Hibernate customer repository definition?
/**
* Created on 30/06/2014.
*/
public interface CustomerRepository extends JpaRepository<Customer, Long> {
public List<Customer> findByEmail(String emailAddress);
public Address findOneByAddressBookId(Long addressId);
}
SOLR Config:
/**
* This class initialises the SOLR repositories.
*/
#Configuration
#EnableSolrRepositories(value = "com.ideafactory", multicoreSupport = true)
public class SolrConfig {
private static final String PROPERTY_NAME_SOLR_SERVER_URL = "solr.server.url";
#Resource
private Environment environment;
#Bean
public SolrServerFactory solrServerFactory() {
return new MulticoreSolrServerFactory(new HttpSolrServer(
environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL)));
}
#Bean
public SolrOperations solrTemplate1() {
SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
solrTemplate.setSolrCore("core1");
return solrTemplate;
}
#Bean
public SolrOperations solrTemplate2() {
SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
solrTemplate.setSolrCore("core2");
return solrTemplate;
}
#Bean
public SolrServer solrServer() throws MalformedURLException, IllegalStateException {
return new HttpSolrServer(environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL));
}
}
The stack trace follows.
17:34:39.966 ERROR org.springframework.web.context.ContextLoader 318 initWebApplicationContext - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) ~[AbstractApplicationContext.class:4.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) ~[AbstractApplicationContext.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381) ~[ContextLoader.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293) [ContextLoader.class:4.0.0.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [ContextLoaderListener.class:4.0.0.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4758) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5184) [catalina.jar:8.0.9]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.9]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724) [catalina.jar:8.0.9]
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700) [catalina.jar:8.0.9]
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714) [catalina.jar:8.0.9]
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1588) [catalina.jar:8.0.9]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) [tomcat-coyote.jar:8.0.9]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_45]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_45]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463) [catalina.jar:8.0.9]
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413) [catalina.jar:8.0.9]
28-Jul-2014 17:34:39.975 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Error listenerStart
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
28-Jul-2014 17:34:39.976 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) [tomcat-coyote.jar:8.0.9]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) [?:1.7.0_45]
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420) [?:1.7.0_45]
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848) [?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_45]
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322) [?:1.7.0_45]
at sun.rmi.transport.Transport$1.run(Transport.java:177) [?:1.7.0_45]
at sun.rmi.transport.Transport$1.run(Transport.java:174) [?:1.7.0_45]
at java.security.AccessController.doPrivileged(Native Method) [?:1.7.0_45]
at sun.rmi.transport.Transport.serviceCall(Transport.java:173) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811) [?:1.7.0_45]
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670) [?:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_45]
at java.lang.Thread.run(Thread.java:744) [?:1.7.0_45]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ideafactory.mvc.customers.model.CustomerRepository com.ideafactory.mvc.customers.admin.AddressController.customerRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
28-Jul-2014 17:34:39.980 WARNING [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.loader.WebappClassLoader.clearReferencesJdbc The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property save found for type Customer!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270) ~[PropertyPath.class:?]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241) ~[PropertyPath.class:?]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) ~[Part.class:?]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213) ~[PartTree$OrPart.class:?]
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321) ~[PartTree$Predicate.class:?]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301) ~[PartTree$Predicate.class:?]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82) ~[PartTree.class:?]
at org.springframework.data.solr.repository.query.PartTreeSolrQuery.<init>(PartTreeSolrQuery.java:36) ~[PartTreeSolrQuery.class:?]
at org.springframework.data.solr.repository.support.SolrRepositoryFactory$SolrQueryLookupStrategy.resolveQuery(SolrRepositoryFactory.java:130) ~[SolrRepositoryFactory$SolrQueryLookupStrategy.class:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320) ~[RepositoryFactorySupport$QueryExecutorMethodInterceptor.class:?]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169) ~[RepositoryFactorySupport.class:?]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224) ~[RepositoryFactoryBeanSupport.class:?]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210) ~[RepositoryFactoryBeanSupport.class:?]
at org.springframework.data.solr.repository.support.SolrRepositoryFactoryBean.afterPropertiesSet(SolrRepositoryFactoryBean.java:66) ~[SolrRepositoryFactoryBean.class:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) ~[AbstractAutowireCapableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) ~[AbstractBeanFactory$1.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[DefaultSingletonBeanRegistry.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) ~[AbstractBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) ~[DefaultListableBeanFactory.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ~[AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[InjectionMetadata.class:4.0.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[AutowiredAnnotationBeanPostProcessor.class:4.0.0.RELEASE]
... 56 more
Ok for reference in case anyone needs it. I don't think I've quite fixed it, or understand why it was happening. But I've worked around this by separating the JPA repositories and SOLR repositories into separate packages, and in the annotation for each explicitly setting the full package directory.
I guess it could just be me not understanding how the repository initialisers work in Spring. So I just changed it to these values and it seems to have at least resolved the first issue:
e.g
#EnableJpaRepositories(basePackages="com.ideafactory.mvc.repositories.jpa")
#EnableSolrRepositories(value = "com.ideafactory.mvc.repositories.solr", multicoreSupport = true)

Hibernate One to many Mapping Error

I'm going to develop hospital management system.in that there is a mapping like below.
doctor can select tablets[selectedTablets] ---> they inserted to Eprescriber form and saved as a record.at begin there is these fields. patient Name & SelectedTablets for him
But when i'm going to develop its gives me a below error.i refer Mkyong Tutorials for my hibernate part.
please help me to sort out this issue.
here is my bean classes. is there any issue with my mappings with my business logic
#Entity
#Table(name = "E_PRESCRIBER")
public class EPrescriber implements Serializable {
private static final long serialVersionUID = 440529869955257543L;
public EPrescriber() {
super();
}
public EPrescriber(int ePrescriberid, List<SelectedTablets> selectedTablets) {
this.ePrescriberid = ePrescriberid;
this.selectedTablets = selectedTablets;
}
#Id
#Column(name = "ePrescriberid" ,unique = true, nullable = false)
#SequenceGenerator(name = "ePrescriber_seq", sequenceName = "ePrescriber_id_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ePrescriber_seq")
private int ePrescriberid;
public int getePrescriberid() {
return ePrescriberid;
}
public void setePrescriberid(int ePrescriberid) {
this.ePrescriberid = ePrescriberid;
}
#Column private String patientName;
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
#OneToMany(fetch = FetchType.LAZY,targetEntity=SelectedTablets.class, mappedBy = "ePrescriberid")
private List<SelectedTablets> selectedTablets=new ArrayList<SelectedTablets>();
public List<SelectedTablets> getSelectedTablets() {
return selectedTablets;
}
public void setSelectedTablets(List<SelectedTablets> selectedTablets) {
this.selectedTablets = selectedTablets;
}
}
another bean class here
#Entity
#Table(name = "SelectedTablets")
public class SelectedTablets implements Serializable {
private static final long serialVersionUID = 4854785134773287611L;
public SelectedTablets() {
}
#Id
#Column(name = "id", unique = true, nullable = false)
#SequenceGenerator(name = "selectedTablets_seq", sequenceName = "selectedTablets_id_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "selectedTablets_seq")
private int id;
#Column private Tablets tablets;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ePrescriberid", nullable = true)
private EPrescriber ePrescriberid;
public EPrescriber getePrescriberid() {
return ePrescriberid;
}
public void setePrescriberid(EPrescriber ePrescriberid) {
this.ePrescriberid = ePrescriberid;
}
public Tablets getTablets() {
return tablets;
}
public void setTablets(Tablets tablets) {
this.tablets = tablets;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
here is the DAO class method. seems here is my issue. ? ? ?
#Repository
#Transactional
public class EPrescriberDAO {
#Autowired
private SessionFactory sessionFactory;
public void getTabletbyNameAndSave(String []selectedMedicines) {
EPrescriber ePrescriber=new EPrescriber();
List<SelectedTablets> selectedTabletsList=new ArrayList<SelectedTablets>();
for (String item : selectedMedicines) {
Tablets tablets=null;
String hql="from Tablets t where t.category='"+item.trim()+"' ";
Query queryList = sessionFactory.getCurrentSession().createQuery(hql);
tablets=(Tablets)queryList.uniqueResult();
SelectedTablets selectedTablets=new SelectedTablets();
selectedTablets.setTablets(tablets);
selectedTablets.setePrescriberid(ePrescriber);
selectedTabletsList.add(selectedTablets);
sessionFactory.getCurrentSession().save(selectedTablets);
}
ePrescriber.setPatientName("Ranil");
ePrescriber.setSelectedTablets(selectedTabletsList);
sessionFactory.getCurrentSession().save(ePrescriber);
}
}
if fault with my DAO, then please advice me too for correct those faults
-thanks
error log
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.priyan.patients.EPrescriber
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:242)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:430)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:265)
at org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:619)
at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3141)
at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:501)
at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:227)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:150)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1142)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:835)
at com.priyan.patients.EPrescriberDAO.getTabletbyNameAndSave(EPrescriberDAO.java:25)
at com.priyan.patients.EPrescriberDAO$$FastClassByCGLIB$$59da35c6.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
at com.priyan.patients.EPrescriberDAO$$EnhancerByCGLIB$$bb3659b.getTabletbyNameAndSave(<generated>)
at com.priyan.patients.ContactsControllers.setTabletsNames(ContactsControllers.java:328)
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.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
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:103)
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.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760)
at java.lang.Thread.run(Unknown Source)
#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinColumn(name = "ePrescriberid", nullable = true)
private EPrescriber ePrescriberid;
SelectedTablets.java edited as above.now my issue sorted & thanks 4 all

Spring: Illegally attempted to associate a proxy with two open Sessions

I have a page to create taxis which consist on a simple form to fill my database. This class and the dao were autogenerated by hibernate tools. When I post my code and it's called the persist method then I get a PersistException The code:
Controller.java
#Controller
#RequestMapping(value="/session/taxi")
public class TaxiController {
private final Log log = LogFactory.getLog(getClass());
#Autowired
private UserManager userManager;
#Autowired
private TaxiManager taxiManager;
/**
* Returns the create taxi page.
* #param model the model on which to map.
* #return A String reference to jsp.
*/
#RequestMapping(value="/create", method=RequestMethod.GET)
public String createTaxi(ModelMap model){
//Add the current business and city to this taxi. It can not be modified
Taxi taxi = taxiManager.createDefaultTaxi();
TaxiPassword taxiPass = new TaxiPassword();
taxiPass.setTaxi(taxi);
model.addAttribute("newTaxi", taxiPass);
return "taxi/createtaxi";
}
/**
* Add a new taxi to the database.
* #param taxiPassword the taxi to be added.
* #param result the result of binding taxi from the model.
* #param redirectAttributes attributes to show messages when redirect.
* #return a string that refers to jsp page.
*/
#RequestMapping(value="/create", method=RequestMethod.POST)
public String addNewTaxi(#ModelAttribute("newTaxi") #Valid TaxiPassword taxiPassword, BindingResult result,
final RedirectAttributes redirectAttributes){
String newPage = "";
Taxi taxi = taxiPassword.getTaxi();
//Check password is correct
if (!result.hasErrors()){
//Set the password as md5
taxi.setPassword(SecurityUtils.getMD5Password(taxi.getPassword()));
//Persist it
taxiManager.persistTaxi(taxiPassword.getTaxi());
newPage = "redirect:/session/taxi/viewtaxi";
}else{
newPage = "taxi/createtaxi";
}
return newPage;
}
}
Taxi.java
#Entity
#Table(name = "taxi", catalog = "takeme", uniqueConstraints = #UniqueConstraint(columnNames = "username"))
public class Taxi implements java.io.Serializable {
#NotNull
#Size(min=1, max=20)
#Digits(integer = 15, fraction = 0)
private String idLicense;
#Valid
private City city;
#Valid
private Business business;
#NotNull
#Nif
private String dni;
#NotNull
#Size(min=3, max=50)
private String username;
#Size(min=5, max=50)
private String password;
#NotNull
#Size(min=1, max=50)
private String name;
#NotNull
#Size(min=1, max=45)
private String surname;
#NotNull
#Size(min=1, max=30)
private String phone;
#NotNull
private boolean creditCardAvailability;
#NotNull
private boolean taxiAdapted;
#NotNull
private boolean bigTaxi;
#NotNull
private boolean availability;
private Double latitude;
private Double longitude;
private byte[] photo;
#NotNull
private boolean state;
private Set<Booking> bookings = new HashSet<Booking>(0);
private Set<MobileClientRateTaxi> mobileClientRateTaxis = new HashSet<MobileClientRateTaxi>(
0);
public Taxi() {
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, boolean state) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.state = state;
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, Double latitude,
Double longitude, byte[] photo, boolean state,
Set<Booking> bookings,
Set<MobileClientRateTaxi> mobileClientRateTaxis) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.latitude = latitude;
this.longitude = longitude;
this.photo = photo;
this.state = state;
this.bookings = bookings;
this.mobileClientRateTaxis = mobileClientRateTaxis;
}
#Id
#Column(name = "id_license", unique = true, nullable = false, length = 20)
public String getIdLicense() {
return this.idLicense;
}
public void setIdLicense(String idLicense) {
this.idLicense = idLicense;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_city", nullable = false)
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
// More autogenerated setters and getters...
}
TaxiDao.java
#Repository(value = "taxiDAO")
public class TaxiDAOImpl implements TaxiDAO{
private final Log log = LogFactory.getLog(getClass());
#PersistenceContext(unitName = "takemePU", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
#Transactional(readOnly = false)
public void persist(Taxi transientInstance) {
log.debug("Persisting taxi instance: " + transientInstance.getIdLicense());
try {
entityManager.persist(transientInstance);
log.debug("Persist successful");
} catch (RuntimeException re) {
log.error("Persist failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public void remove(Taxi persistentInstance) {
log.debug("Removing taxi instance: " + persistentInstance.getIdLicense());
try {
entityManager.remove(persistentInstance);
log.debug("Remove successful");
} catch (RuntimeException re) {
log.error("Remove failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public Taxi merge(Taxi detachedInstance) {
log.debug("Merging taxi instance: " + detachedInstance.getIdLicense());
try {
Taxi result = entityManager.merge(detachedInstance);
log.debug("Merge successful");
return result;
} catch (RuntimeException re) {
log.error("Merge failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findById(String id) {
log.debug("Getting taxi instance with id: " + id);
try {
Taxi instance = entityManager.find(Taxi.class, id);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findByUsername(String username) {
log.debug("Getting taxi instance with id: " + username);
try {
Taxi instance = entityManager.find(Taxi.class, username);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxiList() {
return entityManager.createQuery("select taxi from Taxi taxi").getResultList();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxisByBusiness(String idBusiness) {
return entityManager.createQuery("select taxi from Taxi taxi where taxi.business.idBusiness='"+ idBusiness+"'").getResultList();
}
}
Here is the stacktrace:
javax.persistence.PersistenceException: org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1174)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:674)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366)
com.sun.proxy.$Proxy90.persist(Unknown Source)
com.hp.unileon.takeme.dao.TaxiDAOImpl.persist(TaxiDAOImpl.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy100.persist(Unknown Source)
com.hp.unileon.takeme.service.SimpleTaxiManager.persistTaxi(SimpleTaxiManager.java:19)
com.hp.unileon.takeme.controller.TaxiController.addNewTaxi(TaxiController.java:112)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
If you need any configuration files to know what I am doing wrong tell me, I think it's huge amount of code for now (it has been simplified). Thanks.
UPDATE: my application context is:
<!-- Bean used by the daos to connect and make transactions with the database -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<!-- Activate the annotation driven configurations making useful #Transaction annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.hp.unileon.takeme.service" />
<context:component-scan base-package="com.hp.unileon.takeme.dao" />
<!-- Holding properties for database connectivity -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Enabling annotation driven configuration like #Component-->
<context:annotation-config/>
<!-- Selects the database data source giving username password and nedded parameters
to connect on it. You can change those parameters easily on /classes/messages.properties -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Element that loads tables on the database into object entities and so on -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<!-- This persistence unit can be found on /main/resources/META-INF/persistence.xml -->
<property name="persistenceUnitName" value="takemePU"></property>
</bean>
<!-- Enable hibernate to perform the database operations -->
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}"
p:showSql="${jpa.showSql}"/>
The problem is related to PersistenceContextType.EXTENDED. When I get nested objects from database that use extended persistence context, they open a new session and then are returned by the entityManager. So, if I use them in the same request and try to add to the Taxi entity those nested objects, City and Business belongs to a non clossed session (because scope is EXTENDED) and Taxi belongs to the new session. Persist method does not allow the use of this kind of behabiour because proxy lazy evaluation objects belong to different sessions.
The solution I've finally found is using OpenEntityManagerInViewFilter, that joins all the transactions in the same session. To do it you only have to add this pieze of code in your web.xml.
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Resources