Spring Data JPA. Repositories Inheritance, throws BeanCreationException, NullPointerException - spring

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.

Related

No qualifying bean of type is defined [duplicated]

Currently I experiencing the BeanNameAware interface are not working if AOP is implementing in my Knight Bean.
Why is this happening? because of CGLib conflict? For reference I am using spring framework 3
here is my bean code
public class BraveKnight implements BeanNameAware{
private Quest quest;
public void setQuest(Quest mockQuest){
this.quest = mockQuest;
}
public void embarkOnQuest(){
quest.embark();
}
#Override
public void setBeanName(String beanName) {
System.out.println(beanName +" bean has been initialized..." );
}
}
Application context
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="knight" class="com.springinaction.knights.BraveKnight">
<property name="quest" > <ref bean="quest"/> </property>
</bean>
<bean id="quest" class="com.springinaction.knights.Quest">
<constructor-arg value="#{T(System).out}" />
</bean>
<bean id="minstrel" class="com.springinaction.knights.Minstrel">
<constructor-arg value="#{T(System).out}" />
</bean>
<aop:config>
<aop:aspect ref="minstrel">
<aop:pointcut id="embark" expression="execution(* *.embarkOnQuest(..))" />
<aop:before pointcut-ref="embark" method="singBeforeQuest" />
<aop:after pointcut-ref="embark" method="singAfterQuest" />
</aop:aspect>
</aop:config>
</beans>
[Edit 1]: and here is my main class, I tried getBean with string and class but seems no big differences
public static void main(String[] args) throws Exception{
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring/web/*.xml");
BraveKnight knight = context.getBean(BraveKnight.class);
knight.embarkOnQuest();
context.close();
}
and my result is getting these errors so I am suspecting CGLib conflict with Spring AOP?
quest bean has been initialized...
knight bean has been initialized...
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springinaction.knights.BraveKnight] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:295)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1125)
at com.springinaction.knights.KnightMain.main(KnightMain.java:10)

Spring Autowiring not working - BeanCreationException

I want to integrate Spring with Hibernate. I am new to both technologies. At the moment I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserService controller.HomeController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserService] 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)}
Can anybody help me, please?
package controller;
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping("/register")
public ModelAndView getRegisterForm(#ModelAttribute("user") User user,
BindingResult result) {
ArrayList<String> gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");
ArrayList<String> city = new ArrayList<String>();
city.add("Delhi");
city.add("Kolkata");
city.add("Chennai");
city.add("Bangalore");
Map<String, Object> model = new HashMap<String, Object>();
model.put("gender", gender);
model.put("city", city);
System.out.println("Register Form");
return new ModelAndView("Register", "model", model);
}
#RequestMapping("/saveUser")
public ModelAndView saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
System.out.println("Save User Data");
return new ModelAndView("redirect:/userList.html");
}
#RequestMapping("/userList")
public ModelAndView getUserList() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", userService.getUser());
return new ModelAndView("UserDetails", model);
}
}
package service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void addUser(User user) {
userDao.saveUser(user);
}
#Override
public List<User> getUser() {
return userDao.getUser();
}
}
spring-servlet Code:
Hi need a Spring ,Hibernate integration example for my new project.so i have copied this from a website.and i did some modifications in that ..It's not working please help me
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="controller" />
<tx:annotation-driven/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="myydao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="/user/*.htm" class="controller.HomeController" >
<property name="UserDao" ref="mydao" />
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume that you haven't added the bean to your Spring Application Context
If you are using xml, you need to do this by adding something like the following to the xml file:
<bean class="service.UserServiceImpl" id="userService"/>
Or, if you are using a Java based configuration class, you need to add a bean like so:
#Configuration
public class AppConfig{
#Bean
public UserService userService() {
return new UserServiceImpl();
}
}
Or, if you add the #Component annotation to UserServiceImpl and #ComponentScan("service") annotation to the Java App config, it should pick up the User service
Make sure you have enabled the component scanning to automatically detect classes and register respective beans.
You should add below entry to your bean definition XML file:
<context:component-scan base-package="org.example"/>
More about automatic bean detection

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))
}
...
}

spring el not working with #Transactional

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" />

Spring with JPA pure approch

I have a problem with Spring and JPA. Basically I try to use JPA with Spring with a pure approach, or better, without explicit references in the code to Spring framework with the exception of the #Transactional. So I wanted to know where wrong.
My persistence.xml is:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="fb-persistence" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>it.synclab.fb.jpa.entity.Plugin</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<!-- da utilizzare solo in caso di creazione dello schema <property name="hibernate.hbm2ddl.auto" value="create-drop"/>-->
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.username" value="flussibatch"/>
<property name="hibernate.connection.password" value="caposele"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
</properties>
</persistence-unit>
</persistence>
My applicationContext is:
<?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.0.xsd">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fb-persistence" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean name="pluginDao" class="it.synclab.fb.jpa.dao.impl.PluginDaoImpl" />
</beans>
my DAO interface is:
import it.synclab.fb.jpa.entity.Plugin;
public interface PluginDao {
public Plugin load (int id);
public void save(Plugin plg);
}
and my implementation is:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import it.synclab.fb.jpa.entity.Plugin;
public class PluginDaoImpl implements PluginDao {
private EntityManager entityManager;
#PersistenceContext (unitName="fb-persistence")
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public Plugin load(int id) {
return entityManager.find(Plugin.class, id);
}
#Override
#Transactional
public void save(Plugin plg) {
entityManager.persist(plg);
}
}
This is my "horror":
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: fb-persistence] Unable to configure EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at it.synclab.fb.jpa.test.PluginTest.main(PluginTest.java:26)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: fb-persistence] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:378)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:56)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at org.springframework.orm.jpa.LocalEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalEntityManagerFactoryBean.java:92)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 12 more
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: it.synclab.fb.jpa.entity.StoreFileGet.idTransaction in it.synclab.fb.jpa.entity.Transaction.listStoreFileGet
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:685)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:645)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:65)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1689)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1396)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1348)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1522)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:193)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1100)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:282)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:366)
... 18 more
Caused by: org.hibernate.AnnotationException: mappedBy reference an
unknown target entity property:
it.synclab.fb.jpa.entity.StoreFileGet.idTransaction in
it.synclab.fb.jpa.entity.Transaction.listStoreFileGet
This means that in your entity you have an annotation like this
#OneToMany(mappedBy="something")
In this case, "something" has to be the name of the relevant field of the other entity.
You have only put the it.synclab.fb.jpa.entity.Plugin entity in your persistence.xml, but this entity has an association to another entity (it.synclab.fb.jpa.entity.StoreFileGet), which is not listed. All the entities must be listed.

Resources