How do i tell EclipseLink to stop ServerSession Connection Queries - spring
When looking at my stack trace log, i have noticed that whenever i run any queries using the entity manager or EL (JPA 2.0) provided methods em.find(), findAll() ..., there is an Injected bean from all related entites that trigger n queries depending on the relationship. I have succesfully enabled weaving with tomcat using the spring.instruments jar and i am very sure that weaving is happening and my #OneToOne, #ManyToOne lazy settings are being set and woven in time. The problem might be how i query and the ServerSession connection that executes multiple queries.
The stack trace that shows this :
[EL Fine]: sql: 2012-07-04 22:26:20.959--ServerSession(1528617164)--Connection(1657707912)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (personID = ?)
bind => [101]
2012-07-04 22:26:20,963 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Administrator': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,964 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-04 22:26:20,964 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Administrator': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,965 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.966--ServerSession(1528617164)--Connection(264950364)--Thread(Thread[tomcat-http--9,5,main])--SELECT addressID, CITY, COUNTRY, STATE_US, STREETADDRESS, STREETADDRESS2, version, ZIPCODE FROM ADDRESS WHERE (addressID = ?)
bind => [3]
2012-07-04 22:26:20,970 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Address': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Address.entityManager
2012-07-04 22:26:20,971 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.972--ServerSession(1528617164)--Connection(255059556)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (addressID = ?)
bind => [3]
2012-07-04 22:26:20,975 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Student': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,976 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-04 22:26:20,976 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Student': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,977 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.98--ServerSession(1528617164)--Connection(2062869828)--Thread(Thread[tomcat-http--9,5,main])--SELECT schoolID, ACTIVE, ADMISSIONSEMAILADDRESS, ADMISSIONSPHONE, CODE, description, HELPGENERALEMAILADDRESS, NAME, PRIMARYPHONE, version, addressID FROM SCHOOL WHERE (schoolID = ?)
bind => [3]
2012-07-04 22:26:20,982 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.School': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.School.entityManager
2012-07-04 22:26:20,982 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.983--ServerSession(1528617164)--Connection(140234280)--Thread(Thread[tomcat-http--9,5,main])--SELECT id, ACTIVE, CODE, DESCRIPTION, NAME, version, SCHOOLDEPARTMENT_schoolID FROM DEPARTMENT WHERE (SCHOOLDEPARTMENT_schoolID = ?)
bind => [3]
[EL Fine]: sql: 2012-07-04 22:26:20.986--ServerSession(1528617164)--Connection(1812702959)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (schoolID = ?)
bind => [3]
How to ignore cache and return right away after executing a query on an entity manager object?
#RooJavaBean
#RooToString
#RooJpaActiveRecord(identifierColumn = "addressID")
public class Address {
#Id
#TableGenerator(name = "ADDRESS_TABLE_GEN", table = "ADDRESS_SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "ADDR_SEQ", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "ADDRESS_TABLE_GEN")
#Column(name = "addressID")
private Long id;
#BatchFetch(BatchFetchType.JOIN)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address", fetch = FetchType.EAGER)
private Set<Person> persons = new HashSet<Person>();
Applicant entity
public class Applicant extends Person {
private String major;
#BatchFetch(BatchFetchType.JOIN)
#OneToMany(targetEntity = ApplicantSchool.class, cascade = { javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REMOVE }, mappedBy = "applicant", fetch = FetchType.EAGER)
private Set<ApplicantSchool> schools = new HashSet<ApplicantSchool>();
}
Stack Trace; Reverting a particular OneToOne mapping
[TomcatInstrumentableClassLoader#747917a] error aspect 'org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect' woven into 'org.bixin.dugsi.domain.Registration_Roo_Jpa_ActiveRecord' must be defined to the weaver (placed on the aspectpath, or defined in an aop.xml file if using LTW).
[TomcatInstrumentableClassLoader#747917a] error aspect 'org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl' woven into 'org.bixin.dugsi.domain.Registration_Roo_Jpa_ActiveRecord' must be defined to the weaver (placed on the aspectpath, or defined in an aop.xml file if using LTW).
2012-07-06 17:08:34,910 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [org.bixin.dugsi.domain.Registration]: PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Registration.entityManager
2012-07-06 17:08:34,910 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Registration': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Registration.entityManager
2012-07-06 17:08:34,911 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-06 17:08:34,914 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor#0'
[EL Warning]: metadata: 2012-07-06 17:08:34.968--ServerSession(1433743869)--Thread(Thread["http-bio-8080"-exec-1,5,main])--Reverting the lazy setting on the OneToOne or ManyToOne attribute [person] for the entity class [class org.bixin.dugsi.domain.UserAccount] since weaving was not enabled or did not occur.
This is the field EL is referring to
#OneToOne(targetEntity = Person.class, fetch = FetchType.LAZY)
#JoinColumn
private Person person;
You are specifying FetchType.EAGER in both the relationships you've shown, so they must always be fetched when building the source objects. As mentioned, the problem seems to be reading in Person (or Applicant) which causes Address to be fetched. Chances are that the 'address' ManyToOne in Person is also marked eager. This causes Addresses to be built, and because you have a 1:M from Address->Applicant, this query must go to the database to make sure that it fetched all Applicants.
This same senario happens on all the referenced eagerly fetched entities, and is why it is a bad idea to have everything marked eager unless it is neccessary, especially OneToMany and ManyToMany relationships. I'd recommend you change them to lazy and only fetch them as required when the relationship is accessed, or use fetch join in queries or query hints to prefetch particular relationships that will be needed.
Related
Problem with saving an object with rest template, Spring web app
So I'm building a flashcard app with Spring, JPA, MySQL and using Thymeleaf. At first when i started building I only used MVC. All functionality for saving a new user, a new flashcard and a new topic worked. Now I connected it with a project with a restcontroller and did some modifactions. The problem is that I can't seem to save a new flashcard (although i can save a topic and a user) Can someone spot where i've made a mistake? (note. i have a JPARepository in the backend) #Controller-class //This does not work #PostMapping("/save") public String set(#ModelAttribute Flashcard flashcard){ restTemplate.postForObject("http://localhost:8081/api/card/save", flashcard, Flashcard.class); return "redirect:/"; } //this works #PostMapping("/savePlayer") public String savePlayer(#ModelAttribute Player player){ restTemplate.postForObject("http://localhost:8081/api/player/save", player, Player.class); return "homepage"; } **#RestController-class** #PostMapping("/api/card/save") public Flashcard createFlashcard(#RequestBody Flashcard flashcard) { log.info("New Card added to FlashcardRepository - {}", flashcard); return repository.save(flashcard); } **Flashcard-class** #Id #GeneratedValue(strategy = GenerationType.IDENTITY) #Column(name = "card_id") Long id; String term; String answer; #ManyToOne #JsonBackReference #JoinColumn(name = "topic_id") Topic topic; Error message: 2022-07-15 10:17:41.555 WARN 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000 2022-07-15 10:17:41.556 ERROR 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'topic_id' cannot be null 2022-07-15 10:17:41.608 ERROR 2016 --- [nio-8081-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
Hibernate / Jpa Exception could not reassociate uninitialized transient collection
Searched for hours for a solution to this problem and found absolutely nothing, so now that I have the solution, I'll post this here, so that others don't have to go through the same pain. The following stack trace was caused when I added a #OneToOne mapping to a new entity. What was the cause? 2020-03-17 22:10:26.091 ERROR 46765 --- [ XNIO-12 task-9] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.HibernateException: could not reassociate uninitialized transient collection] 2020-03-17 22:10:26.092 ERROR 46765 --- [ XNIO-12 task-9] my.app.aop.logging.LoggingAspect : Exception in ch.hockai.web.rest.MyEntityResource.updateMyEntity() with cause = 'org.hibernate.HibernateException: could not reassociate uninitialized transient collection' and exception = 'could not reassociate uninitialized transient collection; nested exception is org.hibernate.HibernateException: could not reassociate uninitialized transient collection' org.springframework.orm.jpa.JpaSystemException: could not reassociate uninitialized transient collection; nested exception is org.hibernate.HibernateException: could not reassociate uninitialized transient collection at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:351) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536) <snip/> Caused by: org.hibernate.HibernateException: could not reassociate uninitialized transient collection at org.hibernate.event.internal.ProxyVisitor.reattachCollection(ProxyVisitor.java:75) at org.hibernate.event.internal.WrapVisitor.processCollection(WrapVisitor.java:70) at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104) <snip/>
I have the situation where entity A had a #ManyToOne relationship with entity B. Entity B in turn reciprocated the relationship as a #OneToMany. The problem started when I added entity C with a #OneToOne relationship with entity A. In the end, I removed the #ManyToOne relationship from entity A (to entity B).
Sharing transaction with AbstractRoutingDataSource
I've a problem very close to this one Sharing a transaction while using AbstractRoutingDataSource to switch datasources but I'm not able to solve using the accepted answer. I've a transactional method who have to write the same entity into two different datasource in transactional mode. When transaction commit I've a Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated This is my Transalctional method: #Override #Transactional(propagation = Propagation.REQUIRES_NEW) public ContactTypeJson definisciNuovaContactType(String descrizione) throws Exception { String functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase(); LOGGER.debug("Ho generato la functionCode[" + functionCode + "]"); while (!isContactTypeAvailable(functionCode) || !notificatorService.isFunctionCodeAvailable(functionCode)) { LOGGER.debug("La functionCode[" + functionCode + "] e' gia' in utilizzo, genero una nuova..."); functionCode = RandomStringUtils.randomAlphanumeric(5).toUpperCase(); LOGGER.debug("...la nuova functionCode generata e' [" + functionCode + "]"); } ContactType contactType = new ContactType(); contactType.setName(functionCode); contactType.setDescription(descrizione); notificatorService.insertNewFunction(functionCode, descrizione); entityManagerFRVP0.flush(); entityManagerFRVP0.clear(); VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.FRVP_DATASOURCE); entityManagerFRVP0.persist(contactType); entityManagerFRVP0.flush(); entityManagerFRVP0.clear(); VetrinaContextHolder.setTargetDataSource(VetrinaToolConstants.PWVP_DATASOURCE); ContactType contactType1 = new ContactType(); contactType1.setName(functionCode); contactType1.setDescription(descrizione); entityManagerFRVP0.persist(contactType1); VetrinaContextHolder.clearTargetDataSource(); ContactTypeToJsonConverter converter = new ContactTypeToJsonConverter(); return converter.convert(contactType); } This is the JPA log: 2013-07-15 10:47:59,570 DEBUG [sql] 2013-07-15 10:47:59.569--ServerSession(26361419)--Connection(16434777)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL 2013-07-15 10:47:59,581 DEBUG [sql] 2013-07-15 10:47:59.58--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (81, Prova doppione, 16XOV, NULL) 2013-07-15 10:47:59,596 DEBUG [sql] 2013-07-15 10:47:59.595--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--SELECT VET_SEQ_CONTACT_TYPE.NEXTVAL FROM DUAL 2013-07-15 10:47:59,601 DEBUG [sql] 2013-07-15 10:47:59.6--ClientSession(21299255)--Connection(17900213)--Thread(Thread[[ACTIVE] ExecuteThread: '18' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, Prova doppione, 16XOV, NULL) This the stack: 2013-07-15 10:47:59,421 DEBUG [WebLogicJtaTransactionManager] Creating new transaction with name [com.intesasanpaolo.frvp0.alten.vetrinatool.service.console.ConsoleServiceImpl.definisciNuovaContactType]: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT; '' 2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager 2013-07-15 10:47:59,430 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager 2013-07-15 10:47:59,483 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' 2013-07-15 10:47:59,483 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager' 2013-07-15 10:47:59,483 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction 2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Opening JPA EntityManager 2013-07-15 10:47:59,483 DEBUG [EntityManagerFactoryUtils] Registering transaction synchronization for JPA EntityManager 2013-07-15 10:47:59,542 DEBUG [AnnotationTransactionAttributeSource] Adding transactional method 'insertNewFunction' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' 2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager' 2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction 2013-07-15 10:47:59,543 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager' 2013-07-15 10:47:59,543 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction 2013-07-15 10:47:59,549 DEBUG [TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource] Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' 2013-07-15 10:47:59,549 DEBUG [DefaultListableBeanFactory] Returning cached instance of singleton bean 'transactionManager' 2013-07-15 10:47:59,550 DEBUG [WebLogicJtaTransactionManager] Participating in existing transaction 2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager 2013-07-15 10:47:59,600 DEBUG [EntityManagerFactoryUtils] Closing JPA EntityManager 2013-07-15 10:47:59,600 DEBUG [WebLogicJtaTransactionManager] Initiating transaction commit 2013-07-15 10:47:59,827 DEBUG [DispatcherServlet] Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'jsonView'; model is {hasErrors=true, errorCode=GEN_EX, errorMessages=Errore generico} org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is weblogic.transaction.RollbackException: Unexpected exception in beforeCompletion: sync=org.eclipse.persistence.transaction.JTASynchronizationListener#2f0af4 Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (VETO_PROD.SYS_C0013988) violated Error Code: 1 Call: INSERT INTO S_VET_CONTACT_TYPE (ID, DESCRIPTION, NAME, FASEDIDEFAULT_ID) VALUES (82, 'Prova doppione', '16XOV', NULL) Query: InsertObjectQuery(ContactType [id=82, name=16XOV, description=Prova doppione, fasiAssociate={[]}, faseDiDefault=null]) at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1014) 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:387) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy310.definisciNuovaContactType(Unknown Source) at com.intesasanpaolo.frvp0.alten.vetrinatool.mvc.console.controller.CreaContactTypeController.creaNuovaContactType(CreaContactTypeController.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) I'm using WebLogic 10.3.5 with XA datasources and org.springframework.transaction.jta.WebLogicJtaTransactionManager Any idea?
You are violating a unique constraint. I assume you have one defined on the Contact name, so you cannot insert two contacts with the same name. Trying to switch the connection under a DataSource on the fly seems like a very, very, bad idea. Instead you should have two persistence units, one going to one database, and one going to the other. You may also want to investigate EclipseLink's data partitioning, or composite persistence units. http://wiki.eclipse.org/EclipseLink/Examples/JPA/Partitioning http://wiki.eclipse.org/EclipseLink/Examples/JPA/Composite
#Autowired fails with JUnit & Spring
Really need help. I used JUnit(4.6) plus Spring(3.0.5) for unit testing. When I tried to autowire a service object in my test class, I got a NoSuchBeanDefinitionException. The JUnit code: package com.aaa.service.impl; #ContextConfiguration(locations = { "classpath:/spring/applicationContext.xml", "classpath:/spring/applicationContext-aop.xml", "classpath:/spring/applicationContext-dao.xml", "classpath:/spring/applicationContext-service.xml" }) #RunWith(SpringJUnit4ClassRunner.class) public class TestManageTargetServiceImpl { #Autowired ManageTargetServiceImpl manageTargetServiceImpl; #Test public void testQueryFinancialMonthList() { List<Map<String, Object>> value = new ArrayList<Map<String, Object>>(); ManageTargetDao manageTargetDao = mock(ManageTargetDao.class); when(manageTargetDao.queryFinancialMonthList()).thenReturn(value); manageTargetServiceImpl.setManageTargetDao(manageTargetDao); // I hope it return null assertNull(manageTargetServiceImpl.queryFinancialMonthList()); } } The applicationContext-service.xml code: <context:annotation-config /> <bean id="manageTargetService" class="com.aaa.service.impl.ManageTargetServiceImpl"> <property name="manageTargetDao" ref="manageTargetDao"></property> </bean> The error track: 00:51:28,625 ERROR main context.TestContextManager:324 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#882dfc] to prepare test instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.aaa.service.impl.TestManageTargetServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aaa.service.impl.ManageTargetServiceImpl com.aaa.service.impl.TestManageTargetServiceImpl.manageTargetServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.aaa.service.impl.ManageTargetServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)} Some log: 00:51:26,828 DEBUG main context.TestContextManager:282 - beforeTestClass(): class [class com.aaa.service.impl.TestManageTargetServiceImpl] 00:51:26,828 DEBUG main annotation.ProfileValueUtils:68 - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.aaa.service.impl.TestManageTargetServiceImpl] 00:51:26,828 DEBUG main annotation.ProfileValueUtils:80 - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.aaa.service.impl.TestManageTargetServiceImpl] 00:51:26,828 DEBUG main context.TestContextManager:315 - prepareTestInstance(): instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0] 00:51:26,843 DEBUG main support.DependencyInjectionTestExecutionListener:73 - Performing dependency injection for test context [[TestContext#e0eb3f testClass = TestManageTargetServiceImpl, locations = array<String>['classpath:/spring/applicationContext.xml', 'classpath:/spring/applicationContext-aop.xml', 'classpath:/spring/applicationContext-dao.xml', 'classpath:/spring/applicationContext-service.xml'], testInstance = com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0, testMethod = [null], testException = [null]]]. 00:51:26,843 DEBUG main support.AbstractGenericContextLoader:75 - Loading ApplicationContext for locations [classpath:/spring/applicationContext.xml,classpath:/spring/applicationContext-aop.xml,classpath:/spring/applicationContext-dao.xml,classpath:/spring/applicationContext-service.xml]. 00:51:26,968 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext.xml] 00:51:27,187 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-aop.xml] 00:51:27,312 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-dao.xml] 00:51:27,421 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-service.xml] 00:51:27,453 INFO main support.GenericApplicationContext:456 - Refreshing org.springframework.context.support.GenericApplicationContext#16c14e7: startup date [Tue Jan 01 00:51:27 NZDT 2013]; root of context hierarchy 00:51:27,718 INFO main config.PropertyPlaceholderConfigurer:177 - Loading properties file from class path resource [jdbc.properties] 00:51:27,796 INFO main support.DefaultListableBeanFactory:555 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2938d8: defining beans [loggingAop,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,service,loginDao,manageTargetDao,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,txManager,txAdvice,txDAO,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,loginService,manageTargetService]; root of factory hierarchy
Guessing here - but given that injection of a class type ManageTargetServiceImpl is failing, I think the reason is that a proxy is getting created for ManageTargetServiceImpl and so the type of the bean will not be ManageTargetServiceImpl anymore but the interface of that class. from Biju Kunjummen
Look at your property id. It should be manageTargetServiceImpl in your applicationContext-service.xml Change it to this: <bean id="manageTargetServiceImpl" class="com.aaa.service.impl.ManageTargetServiceImpl"> <property name="manageTargetDao" ref="manageTargetDao"></property> </bean>
Spring #Autowired OK on JUnit, NPE on main class
I have a open source project hosted at this github. I am facing a weird scenario. I found many people who could make #Autowired Spring annotation work on their main classes but not on their JUnit test classes. My problem is the other way around. I can successfully use #Autowired in my JUnit test class but when a test calls my main class, the dependencies don't get injected there. Here is my context (simplified version): Login Class: package net.openrally.restaurant.core.exposure.resource; #Path("/login") #Component #Transactional #Singleton #Produces("application/json") #Consumes("application/json") public class Login extends BaseResource{ #Autowired private UserDAO userDAO; #POST public Response post(String requestBody){ ... //NullPointerException User user = userDAO.loadByCompanyIdAndLogin(companyId, login); } ... } LoginTest Class: package net.openrally.restaurant.core.exposure.resource; #RunWith(SpringJUnit4ClassRunner.class) #ContextConfiguration("/applicationContext.xml") public class LoginTest extends BaseResourceTest { #Autowired private UserDAO userDAO; ... #Test public void testInvalidPassword() { .... // Works perfectly! userDAO.save(user); .... } } applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:configuration.properties</value> </list> </property> </bean> <context:annotation-config /> <context:component-scan base-package="net.openrally.restaurant.core" /> <import resource="db-config.xml" /> </beans> I am searching for a solution for a few days now. From what I could find so far, most of the people who have #Autowired problems dont have either <context:annotation-config /> or xmlns:context="http://www.springframework.org/schema/context" in their spring xml or dont have a #Component family annotation in the class they want DI to take place, and as you can see, they are both there :(. I have only one applicationContext.xml in my project which suits for both runtime and test (I have distinct configuration.properties to set database credentials and log levels differently, but no spring configuration there) I'm using: Spring: 3.1.0.RELEASE JUnit: 4.10 Jersey: 1.11 CLIB: 2.2.2 Any ideas, and I mean ANY :), is much appreciated. UPDATE The following logs come up when I run the test: 2012-03-27 07:37:02,457 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'login' 2012-03-27 07:37:02,457 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'login' 2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [net.openrally.restaurant.core.exposure.resource.Login]: AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.ConfigurationDAO net.openrally.restaurant.core.exposure.resource.Login.configurationDAO 2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [net.openrally.restaurant.core.exposure.resource.Login]: AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.UserDAO net.openrally.restaurant.core.exposure.resource.Login.userDAO 2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'login' to allow for resolving potential circular references 2012-03-27 07:37:02,459 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Getting BeanInfo for class [net.openrally.restaurant.core.exposure.resource.Login] 2012-03-27 07:37:02,462 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Caching PropertyDescriptors for class [net.openrally.restaurant.core.exposure.resource.Login] 2012-03-27 07:37:02,462 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class] 2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'login': AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.ConfigurationDAO net.openrally.restaurant.core.exposure.resource.Login.configurationDAO 2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'configurationDAO' 2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'login' to bean named 'configurationDAO' 2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'login': AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.UserDAO net.openrally.restaurant.core.exposure.resource.Login.userDAO 2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userDAO' 2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'login' to bean named 'userDAO' 2012-03-27 07:37:02,464 DEBUG [main] org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator - Creating implicit proxy for bean 'login' with 0 common interceptors and 1 specific interceptors 2012-03-27 07:37:02,464 DEBUG [main] org.springframework.aop.framework.Cglib2AopProxy - Creating CGLIB2 proxy: target source is SingletonTargetSource for target object [net.openrally.restaurant.core.exposure.resource.Login#60532a0a] 2012-03-27 07:37:02,465 DEBUG [main] org.springframework.aop.framework.Cglib2AopProxy - Unable to apply any optimisations to advised method: public javax.ws.rs.core.Response net.openrally.restaurant.core.exposure.resource.Login.post(java.lang.String) Could Spring be creating my bean correctly but Jersey using its own non-autowired instance?
After researching a while, I could not find a way to make GrizzlyWeb use the context loaded by spring, so I tried to find an alternative solution. I then found Hifaces20, which will let you start and stop a jetty instance, within the same JVM (which means you may, for instance, use a memory database that will be seen both by your tests and your application)
I had the exact same issue and later found that it was a developer issue :) I was creating a new object instead of using the spring bean. Lets say class MyService autowires a dao class MyDao myDaoBean. Now lets say I want to use MyService in MyController, I should wire in the Spring bean myServiceSpringBean. If I try to create a new myServiceObject then Spring doesn't wire the myDaoBean into the myServiceObject because it's not aware about that new service object. And that leads to myDaoBean being null.