spring el not working with #Transactional - spring

faces-config.xml
- org.springframework.web.jsf.DelegatingVariableResolver
applicationContext.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<context:component-scan base-package="com.test"/>
index.xhtml
<h:outputText value="#{authBean.val}"/>
AuthBean.java
package com.test.ui;
#Component
#Scope("session")
public class AuthBean {
#Getter #Setter private String val;
#Transactional public void test(){} //works fine if #Transactional is removed
Works fine,but when a method is annotated with #Transactional,the below error occurs
16:23:13,906 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/jbtst].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: javax.el.PropertyNotFoundException: /index.xhtml #14,49 value="#{authBean.val}": The class '$Proxy28' does not have the property 'val'.
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:111) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIOutput.getValue(UIOutput.java:169) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
Using spring-3.1, hibernate3

When you use #Transactional Spring creates a proxy that implements the same interface as your class, but your AuthBean class doesn't implement an interface.
The easiest way to fix this would be to define an interface with the val property and have AuthBean implement that interface, the proxy will then also have the val property.

This helps annotation equivalent of <aop:scoped-proxy>
<context:component-scan base-package="com.test" scoped-proxy="targetClass" />

Related

Spring MVC Autowired null in Component

My component is:
package com.netpc.recruitment.models.user;
#Component
public class UserAuth {
#Autowired
private HttpSession httpSession;
#Autowired
private IUserDAO userDAO;
}
Vars httpSession and userDAO, while creating object in controllers, are null. userDAO is configured properly and it works fine in my com.netpc.recruitment.controllers.IndexController class #Controller.
My web.xml
<beans ......>
<context:component-scan base-package="com.netpc.recruitment.controllers" />
<bean id="userDAO" class="com.netpc.recruitment.models.user.JDBCUserDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Whats wrong with it? Why it's null?
Your component scan is scanning only on "com.netpc.recruitment.controllers". Should also scan in package com.netpc.recruitment.models.user. Changes in web.xml:
<context:component-scan base-package="com.netpc.recruitment.controllers" />
to this:
<context:component-scan base-package="com.netpc.recruitment.controllers, com.netpc.recruitment.models.user" />
Hope this works for you!

Spring Data JPA. Repositories Inheritance, throws BeanCreationException, NullPointerException

So I started using Spring Data JPA, I find it very easy to use at first especially with simple POJO entities, I managed to perform simple CRUD operations with a single entity (Person), but as I dig deeper with my design(inheritance), I'm starting to have a hard time dealing with Spring JPA repositories when it comes to inheritance design.
Legend :
POJOs
Repositories
Sample class that uses those two above
Exceptions thrown
xml configuration
Person class (base, abstract class)
#MappedSuperclass
public abstract class Person {
..properties, getters and setters with hibernate annotations
}
Student class (child, extends Person)
#Entity
#Table(name = "STUDENT")
public class Student extends Person {
.. properties, getters and setters SPECIFIC for a student
}
REPOSITORIES
PersonRepository (base, parent repository)
public interface PersonRepository<T extends Person, ID extends Serializable> extends JpaRepository<T, ID> {
}
StudentRepository (child, extends PersonRepository)
public interface StudentRepository extends PersonRepository<Student, Integer>{
}
Sample class
#Service ("manager")
public class Manager {
#SuppressWarnings("rawtypes")
#Resource (name = "personRepository")
private PersonRepository personRepository;
#SuppressWarnings("unchecked")
public void savePerson(Person p) {
personRepository.save(p);
}
}
Exceptions thrown
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'manager': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at edu.main.Main.main(Main.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:446)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:420)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:545)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
... 13 more
Caused by: java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:58)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:83)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:66)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:146)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168)
xml Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<context:component-scan base-package="edu.service" />
<jpa:repositories base-package="edu.repository" />
<tx:annotation-driven />
<context:property-placeholder
location="classpath:properties/database.properties"
ignore-unresolvable="false" />
<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>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>edu.domain</value>
</list>
</property>
<property name="persistenceUnitName" value="personPU"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
I'm trying to to find a specific words to search for a similar problem, but no luck, what could be the problem that causes my repository to not have a repository bean(a NullPointerException/BeanCreationException)?. And another thing I want to add, and am I doing something wrong with my design pattern? should I reflect my POJOs inheritance pattern to my Repositories? I'm trying to make my PersonRepository perform operations on my POJO/Entites that are children of the Person class(abstract parent), thats why I came up with the idea of repository inheritance. My specific goal is, Persist/Perform CRUD on any objects that extends the Person using PersonRepository. Any help/suggestion/comments is greatly appreciated. Please. Thank you so much
I believe the PersonRepository should be annotated with #NoRepositoryBean.
In my application I've done it this way:
Parent:
#NoRepositoryBean
public interface UserRepository<T> extends JpaRepository<T, Long> {
}
Child:
#Repository
public interface EmployeeRepository extends UserRepository<Employee> {
}
Hope it helps.

Mixing declarative beans and annotated beans: org.hibernate.HibernateException No Session found for current thread

I get "No Session found for current thread".
I suppose the problem is in mixing declarative xml beans and annotated beans.
Following, I'll resume my config.
MyLibrary Project
Spring 3.1.4
Hibernate 4
applicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan
base-package="com.mycompany.dao.core, com.mycompany.services.core,
com.mycompany.permissionEvaluator" />
<import resource="model-core-security.xml" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
... (sessionFactory ecc...)
model-core-security.xml
<bean id="expressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator" />
</bean>
<security:global-method-security
pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler" />
</security:global-method-security>
With component-scan I create beans: AccountService, AccountDAO and PermissionEvaluator.
AccountService.java (com.mycompany.services)
#Service("accountService")
#Transactional
public class AccountServiceImpl implements AccountService {
#Resource
private AccountDAO accountDAO;
...
}
AccountDAO.java (com.mycompany.dao)
#Repository
#Transactional
public class HibernateAccountDAOImpl implements AccountDAO {
...query...
}
(AccountService e AccountDAO are transactional)
Now, within AccountController.java I call accountService.listAccounts() and it's all right!
But, if I inject AccountService into PermissionEvaluator class (following snippet), AccountController gets No Session found for current thread when invokes accountService.listAccounts()
PermissionEvaluator.java (com.mycompany.permissionEvaluator)
Component("permissionEvaluator")
public class PermissionEvaluatorImpl implements PermissionEvaluator {
#Resource
private AccountService accountService;
...
}
I use PermissionEvaluator (with AccountService, AccountDAO) created by component-scan in expressionHandler bean declared in model-core-security.xml.
Might it be the cause of "no session found for currend thread"?
#Transactional
what's ur import package
import org.springframework.transaction.annotation.Transactional; ??
U can try to import "import javax.transaction.Transactional;"

Injecting EntityManager using Spring ( Null Pointer Exception ) [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
Here's the code insidy my ApplicationContext.xml
<context:spring-configured />
<context:annotation-config />
<context:component-scan base-package="com.apsas.jpa" />
<tx:annotation-driven />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="testjpa" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
and here's my Dao Implementation
public class TeacherDaoImpl implements TeacherDao {
#Autowired
private EntityManager entityManager;
#Transactional
public Teacher addTeacher(Teacher teacher) {
entityManager.persist(teacher);
return teacher;
}
}
Here's my Main Class
public class TestApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"config/ApplicationContext.xml");
TeacherDao teacherDao = new TeacherDaoImpl();
Teacher teacher1 = teacherDao.addTeacher(new Teacher("First Teacher"));
}
}
Please help, i am getting a null pointer exception
Exception in thread "main" java.lang.NullPointerException
at com.apsas.jpa.dao.impl.TeacherDaoImpl.addTeacher(TeacherDaoImpl.java:22)
at com.apsas.jpa.main.TestApp.main(TestApp.java:26)
ive been solving this problem in 2 days but still i cant find any resources that may solve this problem. i appreciate if you give me your opinion,answers or any idea that might help me solving this,
ps: i am new on learning spring
Since you are instantiating TeacherDaoImpl yourself (with the new keyword) within main, Spring is not injecting the EntityManager and hence the NPE.
Annotate the field TeacherDaoImpl.entityManager with #PersistenceContext and annotate the TeacherDaoImpl class with #Component to have Spring instantiate it for you. Then in your main, get a hold of that bean:
TeacherDao dao = applicationContext.getBean(TeacherDao.class);
// ...
Also these two directives seem to be unnecessary:
<context:annotation-config />
<context:spring-configured />
The former is implied when you are using <context:component-scan />. The latter is only useful if you are using #Configurable in your code.
You will want to use #PersistenceContext for injecting the EntityManager.
See
PersistenceContext EntityManager injection NullPointerException
which is pretty much the same question.

java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required in spring+hibernate

I am doing spring + hibernate apllication. When I run the application on tomcat server I am getting some exception. Below is my code.
This is my bean config 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/database/db.properties</value>
</property>
</bean>
<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>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
</bean>
<bean id="employeeBo" class="com.saggezza.employee.bo.impl.EmployeeBoImpl">
<property name="employeeDao" ref="employeeDao" />
</bean>
<bean id="employeeDao" class="com.saggezza.employee.dao.impl.EmployeeDaoImpl">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
this is my dao class.
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
private SessionFactory sessionFactory;
public EmployeeDaoImpl(SessionFactory sessionfactory){
this.sessionFactory=sessionfactory;
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
Here another class employeeBo is calling the employeeDaoImpl.
when I run thisI am getting the below exception.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBo' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Cannot resolve reference to bean 'employeeDao' while setting bean property 'employeeDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao' defined in ServletContext resource [/WEB-INF/spring/EmployeeBean.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
Can anybody help to resolve this. I have tried a lot and google it as well.But did get the solution.
If you have two configuration files, you duplicates 'sessionFactory' definition. Remove one of the 'sessionFactory' definitions . You would have got duplicate bean definition exception before the IllegalArgumentException.
Edit: After your comment,
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
public EmployeeDaoImpl(SessionFactory sessionfactory){
setSessionFactory(sessionfactory);
}
#Override
public List<Employee> getEmployeeDetails() {
return getHibernateTemplate().find("from Employee");
}
}
or get rid of constructor in above code and inject 'sessionFactory' using setter injection.See org.springframework.orm.hibernate3.support.HibernateDaoSupport.setSessionFactory(SessionFactory). I prefer later approach.
I think the problem is the type of SessionFactory you are injecting in EmployeeDaoImpl does not match with the type of the SessionFactory you used in the class.
Can you check it?
This is an old question so must be solved now but still if someone comes across this problem. Following is solution.
You can use Hibernate DAO Support by extending HibernateDAOSupport class and overriding its afterPropertiesSet() method.
This method is called in HibernateDAO support and at that time since sessionFactory is null it is throwing this error. In your custom class you can set this property explicitly and then call the same method of Parent Class (i.e. HibernateDAOSupport's addProperties() method)
package com.techcielo.spring4.hibernate.template;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
#Component("hibernateTemplate")
public class Hibernate4CustomTemplate extends HibernateTemplate{
#Autowired(required=true)
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
System.out.println("Setting SessionFactory");
this.sessionFactory = sessionFactory;
super.setSessionFactory(sessionFactory);
}
#Override
public void afterPropertiesSet() {
System.out.println("Checking if properties set..."+this.sessionFactory);
setSessionFactory(sessionFactory);
super.afterPropertiesSet();
}
}
Following can be used for sample!
I had the same problem and fix it by using Autowired constructor with EntityManagerFactory. Keyur answer is correct
#Service
class EmployeeDaoImpl #Autowired constructor(
factory: EntityManagerFactory
) : HibernateDaoSupport(), EmployeeDao {
init {
if (factory.unwrap(SessionFactory::class.java) == null) {
throw NullPointerException("factory is not a hibernate factory")
}
setSessionFactory(factory.unwrap(SessionFactory::class.java))
}
...
}

Resources