how do i configure spring 2.5.6 + eclipseLink + weblogic 10.3 - spring

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="placeholderPrefix" value="${" />
<property name="placeholderSuffix" value="}" />
<property name="locations">
<value>classpath:ddes/config.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${datasource}"/>
<property name="resourceRef" value="true"/>
</bean>
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.weblogic.WebLogicLoadTimeWeaver"/>
<bean id="PersistenceUnit" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource"/>
<property name="class">
<!--LIST BEANS-->
<value>....</value>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="persistenceUnitManager" ref="PersistenceUnit"/>
<property name="persistenceUnitName" ref="Persistence-ejbPU"/>
<property name="persistenceProvider" ref="org.eclipse.persistence.jpa.PersistenceProvider"/>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="entityManagerFactory"/>
</bean>
implement
#CallByReference
#Stateless(mappedName = "cliente")
public class ClienteDAOBean implements ClienteDAOLocal, ClienteDAORemote {
#PersistenceUnit(unitName = "Persistence-ejbPU")
private EntityManagerFactory emf;
public Clientes find(Integer codCliente) throws Exception {
Clientes cliente = null;
EntityManager em = emf.createEntityManager();
try {
javax.persistence.Query q = em.createNamedQuery("Clientes.findByCodCliente").setParameter("codCliente", codCliente);
cliente = (Clientes) q.getSingleResult();
} catch (Exception e) {
throw e;
} finally {
em.close();
return cliente;
}
}
}
Pero al iniciar la aplicaciĆ³n el log arroja este error:
No persistence unit named 'Persistence-ejbPU' is available in scope Persistence-ejbPU.jar
was previously using a persistence.xml file but needed the name of the datasource out dynamic

Simply replace ref with value. Use:
<property name="persistenceUnitName" value="Persistence-ejbPU" />
instead of:
<property name="persistenceUnitName" ref="Persistence-ejbPU"/>
If you are having still problem then I would implement my own LocalContainerEntityManagerFactoryBean class which extends from AbstractEntityManagerFactoryBean so you can override setPersistenceUnitName then see what is going on.

Related

Bean property 'entityManager' is not writable or has an invalid setter method (using Spring and Hibernate)

Spring and hibernate are both new tools for me and I struggle a bit using both at the same time.
spring.xml :
<bean id="my.supervisionFramesProcess" class="supervision.frames.SupervisionFramesProcess"
init-method="startup" destroy-method="shutdown">
<property name="SupervisionDAO">
<bean class="supervision.dao.jpa.JpaSupervisionDao">
<property name="entityManager" ref="my.entity-manager-factory" />
</bean>
</property>
</bean>
<bean id="my.dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://XXXX/supervision?autoReconnect=true" />
<property name="username" value="***" />
<property name="password" value="***" />
<property name="maxIdle" value="5" />
<property name="maxActive" value="100" />
<property name="maxWait" value="30000" />
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"></bean>
<bean id="my.entity-manager-factory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
<property name="dataSource" ref="my.dataSource" />
<property name="persistenceUnitName" value="SUPERVISION-1.0" />
</bean>
JpaSupervisionDao.xml :
#PersistenceContext(unitName = "SUPERVISION-1.0")
private EntityManager entityManager;
public JpaSupervisionDao() {
if (logger.isDebugEnabled())
logger.debug("New instance DAO : " + this);
}
protected void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
protected EntityManager getEntityManager() {
return entityManager;
}
#Override
public SupervisionDbObject selectSupervisionDbObject(SupervisionDbObject supervision) {
Query query = getEntityManager().createQuery(SELECT_SUPERVISION);
}
persistence.xml :
<persistence-unit name="SUPERVISION-1.0">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>supervision.dao.SupervisionDbObject</class>
</persistence-unit>
Using JDBC, my DataSource can be instanciated and is fully working but using Hibernate and the entityManager, i only get an error :
Bean property 'entityManager' is not writable or has an invalid setter method.
I have tried to use the EntityManagerFactory object instead but the same error occurs.
Can someone help me out ?
The addition of the <context:annotation-config/> fixed my issue thanks to M. Deinum's answer.
If this can help someone else, I also had an issue with an import, I was importing
org.hibernate.annotations.Entity instead of javax.persistence.Entity.

Spring data-jpa Transactional does not work on service

Here is my service method:
#Resource
private PersonRepository personRepository;
#Transactional
#Override
public Person create(PersonDTO created) {
LOGGER.debug("Creating a new person with information: " + created);
Person person = Person.getBuilder(created.getFirstName(), created.getLastName()).build();
personRepository.save(person);
foo();
return null;
}
public void foo() {
throw new RuntimeException();
}
As you can see i'm throwing an execption but persistancy takes place non the less.
Here is my datasource config:
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/dbb"/>
<property name="username" value="root" />
<property name="password" value="pass" />
<property name="initialSize" value="10"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="15"/>
<property name="minIdle" value="10"/>
<property name="timeBetweenEvictionRunsMillis" value="10000"/>
<property name="minEvictableIdleTimeMillis" value="60000"/>
<property name="validationQuery" value="/* ping */ SELECT 1"/>
<property name="testOnBorrow" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="300"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<!-- <property name="databasePlatform" value="${hibernate.dialect}"/> -->
<property name="showSql" value="false"/>
<property name="generateDdl" value="false"/>
<!-- <property name="hibernate.connection.autocommit" value="false"/> -->
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.connection.autocommit" value="false" />
</map>
</property>
</bean>
Any idea why?
Thanks!
You have to throw TransactionSystemException of Spring. Otherwise, you have to throw own exception that extend TransactionSystemException.
Example :
import org.springframework.transaction.TransactionSystemException;
public class SystemException extends TransactionSystemException {
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable throwable) {
super(message, throwable);
}
}
public void foo() {
throw new SystemException("System Error!");
}

Hibernate + Spring two persistence units with their own entity subsets

I am new to Spring but in general I am aware of it's features so I decided to use it in one of my projects. Main problem however is with Hibernate. Before this idea of introducing spring the premise is this:
My application (not web) had to connect to a DB and gather information from it using "persistence_1.xml" with it's own set of entity classes. In other words everything related to "persistence_1.xml" was read only so that no tragedies would occur. Also "persistence_1.xml" with persistence-unit of name "p1" came from web-app dependencies. So picture is this: my app (not-web) written with the support of maven, took dependencies of the other application to access database and gather information.
And the other "persistence_2.xml" with persistence-unit name of "p2" and it's own subset of entities was created by me to store gathered and processed information into the same database.
So originally I had two entity managers one responsible for "p1" another for "p2".
I have seen some material on the internet where they show how to configure two entity managers with different dataSources but I can not figure out how to create two entity managers in SPRING using their own set of ENTITIES.
Let's say "test" is only associated with "UserEntity" and "dummy" is only associted with "DumbEntity".
Now everything get's mashed up along the way and no matter which PU name I type in in #PersistenceContext(name = "test") - it can query for any entity in database.
This is example of persistence.xml:
<persistence-unit name="test" type="RESOURCE_LOCAL">
<class>org.test.db.UserEntity</class>
</persistence-unit>
<persistence-unit name="dummy" type="RESOURCE_LOCAL">
<class>org.test.db.DumbEntity</class>
</persistence-unit>
Bean definition:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="test" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="entityManagerFactory2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="dummy" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory2"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean name="userDao" class="org.test.services.UserDaoImpl" />
My UserDaro service
public class UserDaoImpl implements UserDao {
#PersistenceContext(unitName = "test")
private EntityManager entityManager;
public UserDaoImpl() {
}
public UserDaoImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
#Override
public void saveUser(UserEntity user) {
entityManager.persist(user);
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
#Override
public void saveUser(DumbEntity user) {
entityManager.persist(user);
}
#Override
public List<UserEntity> fetchAllUsers() {
String sql = "FROM UserEntity";
Query query = entityManager.createQuery(sql);
return query.getResultList();
}
#Override
public List<DumbEntity> fetchAllUsers2() {
String sql = "FROM DumbEntity";
Query query = entityManager.createQuery(sql);
return query.getResultList();
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
In any way whether or not I use fetchAllUsers() or fetchAllUsers2() I get the result, but I would like that each of these would only work with entityManager that only has the knowledge about about specific entities.
I would like you to share your thoughts on this one. Thank You.

Spring 3 doesn't inject DAO bean

I'm using Spring 3 and UserServiceImpl. The service does not see the Dao bean.
This is my UserDao:
#Repository
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
}
Then the Service bean :
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public String testeoDAO() {
return userDao.funciona();
}
}
The testeoDAO method had writeen only for testing the DAO.The applicationContext
<context:annotation-config/>
<bean id="userDao" class="com.apress.usermanager.dao.hibernate.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userService" class="com.apress.usermanager.service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
autowire="byName">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.apress.usermanager"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.query.substitutions=true 'Y', false 'N'
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.hbm2ddl.auto=update
hibernate.use_sql_comments=true
hibernate.show_sql=true
hibernate.current_session_context_class=thread
</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="100"/>
<property name="maxWait" value="1000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="defaultAutoCommit" value="true"/>
<property name="testOnBorrow" value="true"/>
<property name="validationQuery" value="select 1=1"/>
</bean>
<bean id="staticDataImporter" class="com.apress.usermanager.support.StaticDataImporter" depends-on="sessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="staticData" value="classpath:default-data.xml"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
And the error :
java.lang.NullPointerException
at com.apress.usermanager.service.UserServiceImpl.testeoDAO(UserServiceImpl.java:49)
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 think you need to add
<context:component-scan base-package="com.a,com.b">
</context:component-scan>
To scan package com.a and com.b. This allows the classpath scan and add all #Component and so forth to it.
Annote UserServiceImpl with #Service.
Regards.

entitymanager is null on DAO class

I am trying to implement Spring MVC 3 +EclipseLink JPA 2
When I call saveUser for example it returns that
NullPointerException, EntityManager is
null
:
public class UserDAO {
#PersistenceContext
private EntityManager em;
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Transactional
public User saveUser(User user){
return em.merge(user);
}
My config is:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="application" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value=".." />
<property name="password" value=".." />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://..." />
</bean>
Also have
<context:component-scan base-package="com.elasticbeanstalk.mypackage" />
<context:annotation-config />
It does initialize JPA during Tomcat startup. Why am I see NPE? Could I miss something?
If you instantiate the UserDAO manually, nothing will be injected by Spring. If the DAO is in a package which is under your base-package of <context:component-scan ../> then you can simply autowire it into your Controller. If not, either modify the base-package or also you can define the DAO in the appcontext manually, then you can autowire as well.

Resources