#PostConstruct not called (Primefaces & Spring & Hibernate) - spring

I'm using Hibernate, Spring and Primefaces (and Maven) and I'm trying to run
#PostConstruct
init() {}
to initialize a location list inside a bean. But the init() method is never called. The projects structure is:
com.xxx
com.xxx.hibernate.dao
com.xxx.hibernate.dao.impl
com.xxx.hibernate.data
com.xxx.prime.faces.bean
com.xxx.spring.service
com.xxx.spring.service.impl
application context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:property-placeholder location="classpath*:META-INF/*.properties"/>
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.xxx"></context:component-scan>
<!-- Create Data Source bean -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://host:3306/db" />
<property name="username" value="user" />
<property name="password" value="password" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property value="persistenceUnit" name="persistenceUnitName" />
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Detect #Transactional Annotation -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
The LocationView Bean:
#ManagedBean
#ViewScoped
public class LocationView implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty("#{locationService}")
private LocationService locationService;
private Location location = new Location();
private List<Location> locations = new ArrayList<Location>();
#PostConstruct
public void init() {
this.locations = locationService.getAllLocations();
}
I run this on Glassfish4 in debug mode and the init() Method is never called. but I don't no why. It should be scanned for spring annotations, but I don't know how I could be sure about that.
Also I'm not sure what
<context:property-placeholder location="classpath*:META-INF/*.properties"/>
does.
Any ideas what I could check?

Related

single jpa transaction manager for multiple entitymanagers

#Repository
#Transactional
#Scope("prototype")
public class EntityManagerImpl implements EntityManagerGenerator {
#PersistenceContext(unitName = "test")
#Qualifier("transactionManager")
private EntityManager entityManager;
#PersistenceContext(unitName = "test1")
#Qualifier("transactionManager1")
private EntityManager entityManager2;
#Override
public EntityManager getEntityManager(String userType) {
if(userType.equals("test")){
return entityManager2;
}else{
return entityManager;
}
}
here how to use according entitymanager wise transaction manager dynamically.below i shared my xml configure file.
<?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"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="entityManagerFactory2"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="test1.ds" />
<property name="persistenceUnitName" value="test1" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapterFC" />
<property name="persistenceXmlLocation" value="classpath:jpa-persistence.xml" />
</bean>
<bean id="jpaVendorAdapterFC"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="false" />
</bean>
<bean id="transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory2" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml" />
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative
to JTA) -->
<!-- Activates various annotations to be detected in bean classes: Spring's
#Required and #Autowired, as well as JSR 250's #PostConstruct, #PreDestroy
and #Resource (if available) and JPA's #PersistenceContext and #PersistenceUnit
(if available). -->
<context:component-scan base-package="com.wmi.test" annotation-config="true"
scope-resolver="org.springframework.context.annotation.Jsr330ScopeMetadataResolver"/>
<!-- Instruct Spring to perform declarative transaction management automatically
on annotated classes. -->
<tx:annotation-driven />
<cache:annotation-driven />
so how can i use single transaction manager for multiple data source according to my configuration
and here we are used for transactional manager as #Transactional annotation

Spring data jpa + Spring Transaction for multiple database

I am implementing multiple transaction(database) for my service using spring data jpa with #Transaction, having two persistent Unit names. And deploying in Jboss 6.4 EAP
spring xml includes
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.test.demo.domain.service" />
<context:component-scan base-package="com.test.demo.domain" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="demo-domain" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
</bean>
<bean id="entityManagerFactoryMeta"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="demo-meta" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<qualifier value="demoadmin"/>
</bean>
<bean id="transactionManagerMeta" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryMeta" />
<qualifier value="demoappmeta"/>
</bean>
<jpa:repositories base-package="com.test.demo.domain.repository" />
</beans>
Below are my service details
#Named(ServerConstants.SERVICE_DRAG_DROP)
**#Transactional("demoappmeta")**
public class DragDropService {
private static final Logger LOG = LoggerFactory.getLoggerFactory().getDomainLogger(ServerConstants.LOGGER_DOMAIN, DragDropService.class.toString());
#Inject
private TbAsmiDragDropRepository dragDropRepo;
public void createDragDrop(Message pMessage){
JSONObject requestJson = pMessage.getRequestObject().getRequestJson();
LOG.debug("inside createDragDrop() - Request : "+requestJson);
In Jboss I am unable to deploy it, I get the following exception:
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private
com.test.demo.domain.repository.TbAsmiDragDropRepository
com.test.demo.domain.service.DragDropService.dragDropRepo; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'tbAsmiDragDropRepository': Invocation
of init method failed; nested exception is
java.lang.IllegalArgumentException: Not an managed type: class
com.test.demo.domain.entity.TbAsmiDragDrop
If anything is missing or something is wrong, please advise
I found the solution just we have to set the attribute entity-manager-factory-ref="entitymanagerfactoryrefname" in
<jpa:repositories base-package="com.test.demo.domain.repository" entity-manager-factory-ref="entitymanagerfactoryrefname" />

Spring Transaction not working

I'm having a problem with transactions, when execution reaches
taskExecutor.execute();
I get an Exception:
Caused by: org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
I know this error is self-explanatory, but I can't get it to work properly.
This is how I get the controller and make the call:
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml");
BeanFactory beanFactory = context;
FacadeControler f = beanFactory.getBean("facadeController");
f.method(reservation);
This is my FacadeController:
package xxx;
import ...
#Service
public class FacadeControllerImpl implements FacadeController {
static Logger logger = Logger.getLogger(FacadeControllerImpl.class);
#Qualifier("executor")
#Autowired
private TaskExecutor taskExecutor;
#Transactional(propagation=Propagation.REQUIRED)
public Reservation method(Reservation reservationFromEndpoint){
...
taskExecutor.execute();
...
}
Here is the Executor:
#Component("executor")
public class QueueTaskExecutor implements TaskExecutor {
final static Logger logger = LoggerFactory.getLogger(QueueTaskExecutor.class);
#Autowired
protected QueuedTaskHolderDao queuedTaskDao;
#Autowired
protected Serializer serializer;
#Override
#Transactional(propagation=Propagation.MANDATORY)
public void execute(Runnable task) {
logger.debug("Trying to enqueue: {}", task);
AbstractBaseTask abt;
try {
abt = AbstractBaseTask.class.cast(task);
} catch (ClassCastException e) {
logger.error("Only runnables that extends AbstractBaseTask are accepted.");
throw new IllegalArgumentException("Invalid task: " + task);
}
// Serialize the task
QueuedTaskHolder newTask = new QueuedTaskHolder();
byte[] serializedTask = this.serializer.serializeObject(abt);
newTask.setTriggerStamp(abt.getTriggerStamp());
logger.debug("New serialized task takes {} bytes", serializedTask.length);
newTask.setSerializedTask(serializedTask);
// Store it in the db
this.queuedTaskDao.persist(newTask);
// POST: Task has been enqueued
}
}
Here is my 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"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Where to look for Spring components -->
<context:annotation-config />
<context:component-scan base-package="com.xxx"/>
<!-- #Configurable with AspectJ -->
<context:spring-configured/>
<!-- A task scheduler that will call #Scheduled methods -->
<!-- <task:scheduler id="myScheduler" pool-size="10"/> -->
<!-- <task:annotation-driven scheduler="myScheduler"/> -->
<!-- DataSource -->
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="myDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/bbdd"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<!-- JPA Entity Manager -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="myEntityManagerFactory">
<property name="dataSource" ref="myDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"></bean>
</property>
<property name="persistenceUnitName" value="comm_layer" />
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false"/>
<entry key="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<entry key="eclipselink.logging.level" value="INFO"/>
</map>
</property>
</bean>
<!-- Transaction management -->
<tx:annotation-driven mode="aspectj" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
<property name="entityManagerFactory" ref="myEntityManagerFactory"/>
</bean>
<bean id="facadeController" class="xxx.FacadeControllerImpl">

NullPointerException from DAO by using crudRepositoy

i got java.lang.NullPointerException by using CrudRepository
my project looks like this:
strut2 action
service
repository
domain
class Action {
#Autowired MyService service;
public String execute(){
service.getList();
return "ok";
}
}
interface Service {
List getList();
}
#org.springframework.stereotype.Service
class ServiceImpl implements Service {
#Autowired MyRepository repo;
List getList(){
return (List)repo.findAll();
}
}
package com.mycompany.repositories;
interface MyRepository extends CrudRepository<MyPojo, String>{}
here is the config:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.mycompany.repositories" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="unit-name" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="POSTGRESQL"/>
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/mydb" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"></bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
I'm new here, and everytime i call the Action class, the service is injected, but MyRepository is alway null.
could someone help me with please, if you need more infos, pls let me know, thx!
EDIT 1
StackTrace:
2012-06-26 15:33:32,041 INFO - com.myproject.action.project.preparation.ApplicationAction - listing application...
java.lang.NullPointerException
at com.myproject.service.impl.ApmProjectPreparationServiceImpl.getAllApplications(ProjectPreparationServiceImpl.java:41)
at com.myproject.action.project.preparation.ApplicationAction.listAction(ApplicationAction.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
I also tried to debug it by myself. i found on the class ServiceImpl that the #Autowired MyRepository repo is null.
Seems i found the answer, thank #MartenDeinum from Spring Forum.
here are the tricks:
i am using struts2 for the GUI, so i need struts2 spring plugin to rewrite the struts2 object factory, so that the spring can find struts action.
i added this config for #Service
<context:component-scan base-package="com.myproject" />
basically i also need
<jpa:repositories base-package="com.myproject.repository" />
to find CrudRepository.
hope this can help others.

Spring jpa transaction business to Dao

business layer:
public class ServiceImpl implements Service{
#Transactional(readOnly = false)
public void createOrUpdateAppPing(String s) {
servicePingDao.createOrUpdateAppPing(s);
}
}
Dao layer
public void createOrUpdateAppPing(String sc) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
pingScService(sc,entityManager);
if(ifHasPingScConfig(sc,entityManager)) {
updateScConfig(sc,entityManager);
} else {
createScConfig(sc,entityManager); }
entityManager.close();
}
here :
** pingScService has select query
** updateScConfig - update query
** createScConfig-insert
config service-datasorce.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:osgi="http://www.springframework.org/schema/osgi"
xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
xmlns:ctx="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/osgi-compendium
http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd
">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="smx4" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="com.luthresearch.savvyconnect.model.PostgreSQLDialectUuid" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver.class}" />
<property name="url" value="${database.savvyconnect.url}" />
<property name="username" value="${database.savvyconnect.username}" />
<property name="password" value="${database.savvyconnect.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
IN service.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:osgi="http://www.springframework.org/schema/osgi"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="service"
class="com.services.impl.SServicempl" autowire="byName">
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Now i want to add transaction support at service layer ...How i can do this.
I tried adding #Transaction annotation but I am getting
javax.persistence.TransactionRequiredException: Executing an update/delete query

Resources