JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory - eclipse

I have a problem with Java Persistence API and Hibernate.
My situation of project is:
My persistence.xml file 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="JPA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.david.Libro</class>
<class>com.david.Categoria</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="javax.persistence.transactionType" value="RESOURCE_LOCAL" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/arquitecturaJava" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>
And i create EntityManagerFactory in:
private static EntityManagerFactory buildEntityManagerFactory()
{
try
{
return Persistence.createEntityManagerFactory("JPA");
}
catch (Throwable ex)
{
ex.printStackTrace();
//throw new RuntimeException("Error al crear la factoria de JPA:->"+ ex.getMessage());
}
}
My error is about create EntityManagerFactory:
javax.persistence.PersistenceException: [PersistenceUnit: JPA] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.david.JPAHelper.buildEntityManagerFactory(JPAHelper.java:14)
at com.david.JPAHelper.<clinit>(JPAHelper.java:8)
at com.david.Categoria.buscarTodos(Categoria.java:93)
at com.david.FormularioInsertarLibroAccion.ejecutar(FormularioInsertarLibroAccion.java:25)
at com.david.ControladorLibros.doGet(ControladorLibros.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.david.Libro
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2638)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:706)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3512)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3466)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1355)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 27 more
Part of Libro and Categoria classes code is:
#Entity
#Table(name = "Categorias")
public class Categoria implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "categoria")
private String id;
private String descripcion;
....
and
#Entity
#Table(name="Libros")
public class Libro implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
private String isbn;
private String titulo;
#ManyToOne
#JoinColumn (name="categoria")
private Categoria categoria;
....
My file of Hibernate Configuration is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/arquitecturajava</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<mapping class="com.david.Categoria"></mapping>
<mapping class="com.david.Libro"></mapping>
</session-factory>
</hibernate-configuration>
Any ideas!!
ThankĀ“s!!

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?
But as the other answer also pointed out, this is not okay like this:
#Id
#JoinColumn(name = "categoria")
private String id;
Didn't you want to use #Column instead?

Suppress the #JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory
** This is a solution if you are using Audit table.#Audit
Use:- #Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.

It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>

Related

Unable to build entity manager factory - Rest Tomcat Jpa

I'm making a Restful web service using netbeans, tomcat, jpa and jax-rs. I have this error since I've add the <class /> tags to my persistence.xml for all of my classes (And I need them to make a select).
The error is : https://gist.github.com/anonymous/bb37c28cdb3dbdf721c5206bfa6369c3
And my persistence.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="NataRestServicePU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>model.Media</class>
<class>model.MediaTypeDB</class>
<class>model.Message</class>
<class>model.Observation</class>
<class>model.Session</class>
<class>model.Species</class>
<class>model.User</class>
<class>model.UserType</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/natagora?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
And this is the main dao (that worked before, didn't change anything) but without all the CRUD methods (just the read for example)
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
public class MainDAO<T> implements IMainDAO<T> {
protected Class<T> clazz;
private final EntityManagerFactory factory;
private static final String PERSISTENCE_UNIT_NAME = "NataRestServicePU";
#PersistenceContext(unitName = "NataRestServicePU")
protected EntityManager entityManager;
public MainDAO(Class<T> type){
clazz = type;
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
#Override
public T read(int id){
try{
newEntityManager();
return entityManager.find(clazz,id);
}finally{
closeEntityManager();
}
}
protected void closeEntityManager(){
entityManager.close();
}
protected void newEntityManager(){
entityManager = factory.createEntityManager();
}
}

java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName CarLocPU

I'm beginning Java EE with NetBeans 8.1, Glassfish 4.1 and Apache Derby (included in GlassFish).
For this purpose I'm calling to put and store a car data with its attributes.
But this simple facade always returns "java.lang.IllegalStateException" whereas I'm seeing no mistakes in my Class files.
Here is the very simple Entity of model.car with basic getters and setters :
#Entity
#Table(name = "car")
public class Car implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String brand;
private String model;
private String year;
private String energy;
private String hp;
private String tp;
private byte[] picture;
Here is the "Facade" for this Entity to store data in Apache Derby :
#Stateless
public class CarFacade extends AbstractFacade<Car> {
#PersistenceContext(unitName = "CarLocPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CarFacade() {
super(Car.class);
}
}
I'm having a lot of trouble debugging the following exception since it is very simple short part of code and everything should works fine. Moreover, the StackTrace doesn't show the breaking point like in Java SE.
Here is the exception StackTrace :
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName CarLocPU
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at facade.AbstractFacade.create(AbstractFacade.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor965.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor994.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 53 more
Thank you in advance for you help.
EDIT :
Here is the structure of the project.
And here is the persistence.xml content, the application is named "CarLoc".
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="CarLocPU" transaction-type="JTA">
<jta-data-source>java:app/jdbc/CarLoc</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
If you are using JPA outside of the EJB container, you need to declare a JPA <provider> in your persistence.xml.
By default Glassfish uses EclipseLink as the JPA provider. Assuming you don't want to change this, you will want to change your persistence.xml to declare EclipseLink as the JPA provider:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="CarLocPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="Derby"/>
<!-- JDBC connection properties -->
<property name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/myDBName;create=true;"/>
<property name="eclipselink.jdbc.user" value="APP"/>
<property name="eclipselink.jdbc.password" value="APP"/>
</properties>
</persistence-unit>
</persistence>
Source:
Oracle Docs - Chapter 7 Using the Java Persistence API

Spring data Jpa JavaConfig

i'm working on a spring web application using spring data jpa lately
i have problems with the persistence configuration :
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = "com.servmed")
#PropertySource({ "/resources/hibernate.properties" })
#EnableJpaRepositories(basePackages = "com.servmed.repositories")
public class PersistenceConfig {
#Autowired
private Environment env;
Properties jpaProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); //allows Hibernate to generate SQL optimized for a particular relational database.
setProperty("hibernate.show_sql",env.getProperty("hibernate.show_sql"));
}
};
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaProperties(jpaProperties());
factory.setPackagesToScan("com.servmed.models");
//factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}
#Bean
public PlatformTransactionManager transactionManager()
{
EntityManagerFactory factory = entityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
}
i get this error and i can't seem to find what's wrong :
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/servmed/configuration/PersistenceConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory]]
PS: i noticed that the hibernate entity manger i added to libraries is depecated , should i replace with something else ?
Not entirely sure what the problem is but I believe your entity manager definition might be busted somewhere.
I use this definition that is pretty close to your. Have a look.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(this.dataSource());
emf.setPackagesToScan("com.servmed.models");
emf.setPersistenceUnitName("MyPU");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(va);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
jpaProperties.put("hibernate.hbm2ddl.auto", "create");
emf.setJpaProperties(jpaProperties);
emf.afterPropertiesSet();
return emf;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<context:annotation-config/>
<context:component-scan base-package="com.wish.anthem.hippa" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.wish.anthem.hippa.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${jpa.showSql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</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="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- <tx:annotation-driven /> -->
<!-- <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
</beans>
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/anthem
jdbc.username=root
jdbc.password=
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
<jsp:forward page="anthemlogin.htm" />
#SuppressWarnings("unchecked")
#Repository
public class CatalogDaoImpl implements CatalogDao
{
#Autowired
private SessionFactory sessionFactory;
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
#Transactional
public List<Catalog> getAllCatalogs()
{
Session session = sessionFactory.openSession();
Query query = session.createQuery("select c from Catalog c");
List<Catalog> catalogs = query.list();
session.close();
return catalogs;
}
}
#Entity
#Table(name = "h_product")
public class Product implements Serializable
{
private static final long serialVersionUID = 353305417649482096L;
#Id
#GeneratedValue
#Column(name = "ProductID", nullable = false)
private Integer productID = 0;
#Column(name = "ProductItem", nullable = false, length = 50)
private String productItem = "";
#Column(name = "ProductName", nullable = false, length = 50)
private String productName = "";
#Column(name="Title", nullable=false, length=50)
private String title = "";
#Column(name = "CreateTime", nullable = false, length = 19)
private Date createTime = Utils.getCurrentDateTimeDate();
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public String getProductItem() {
return productItem;
}
public void setProductItem(String productItem) {
this.productItem = productItem;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((productID == null) ? 0 : productID.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (productID == null)
{
if (other.productID != null)
return false;
}
else if (!productID.equals(other.productID))
return false;
return true;
}
}
#Component
public class HippaServiceImpl implements HippaService
{
#Autowired
private HippaDao catalogDao;
}
#Controller
public class HippaController
{
final static Logger logger = Logger.getLogger(HippaController.class);
#Autowired
private HippaService hippaService;
#RequestMapping(value="/anthemlogin", method = RequestMethod.GET)
public String showLoginPage(HttpServletRequest request,HttpSession session)
{
logger.info("Home Page!!!!!!!!");
return "home";
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="minPoolSize" value="${jdbc.miniPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" />
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}" />
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" />
<property name="preferredTestQuery" value="${jdbc.preferredTestQuery}" />
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
</bean>
<!-- JPA EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.search.default.directory_provider">${hibernate.search.default.directory_provider}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:component-scan base-package="com.wish" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
jdbc.miniPoolSize=1
jdbc.maxPoolSize=10
jdbc.initialPoolSize=1
jdbc.maxIdleTime=21600
jdbc.acquireIncrement=1
jdbc.acquireRetryAttempts=30
jdbc.acquireRetryDelay=1000
jdbc.testConnectionOnCheckin=true
jdbc.preferredTestQuery=select 1
jdbc.idleConnectionTestPeriod=3600
hibernate.search.default.directory_provider=com.wish.common.resource.hibernate.search.WishFSDirectoryProvider
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=30
hibernate.default_batch_fetch_size=8
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bbcrafts?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
#Service
public class OrderDao implements IOrderDao
{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Order> getOrdersForTracking(String orderCode, String realName) throws RuntimeException
{
StringBuffer sql = new StringBuffer("select o from Order o");
sql.append(" where (o.orderCode = ?1) and (o.billingRealName like concat('%',?2,'%')");
sql.append(" or o.shippingRealName like concat('%',?3,'%'))");
sql.append(" order by o.dateTime desc");
Query query = em.createQuery(sql.toString());
query.setParameter(1, orderCode);
query.setParameter(2, realName);
query.setParameter(3, realName);
return query.getResultList();
}
TO find: Order temp = em.find(Order.class, orderID);
return temp != null ? temp : new Order();
Libs:
activation-1.1, antlr-2.7.6, antlr-runtime-3.0, aopappliance-1.0, apache-lucene, commons-collections-3.1, commons-io-2.0.1, commons-logging-1.0.4, dom4j, ejb3-persistence-1.0.2.GA, hibernate3, hibernate-annoatation-3.4.0.GA, hibernate-commons-annoatation-3.1.0.GA, hibernate-core-3.3.2.GA, hibernate-entitymanager-3.4.0.GA, hibernate-search-3.1.1.GA, hibernate-validator-3.1.0.GA, javax.transaction, jstl-1.2, log4j, log4j-1.2.13, logback, javaassist-3.4.GA, jackson-all-1.9.0, IKanalyzer-3.1.2.GA, mysql-connector-java-5.1.18-bin, org-apache-commons-logging, pinyin4j-2.5.0, slf4j-api-1.7.9, all spring jars

Getting a null pointer exception for mongoTemplate instance in Spring mvc

I am creating a simple login functionality using Spring with MongoDB. In my spring-context.xml, i defined the configuration for mongo but when I am using it inside my controller, it is showing null pointer Exception.
Spring-context.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:c="http://www.springframework.org/schema/c" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="Controller" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<mongo:mongo host="localhost" port="27017">
<mongo:options
connections-per-host="5"
connect-timeout="30000"
max-wait-time="10000"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<mongo:db-factory dbname="Test"
mongo-ref="mongo"
/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Controller:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
private DBCollection getCollection(String collectionName)
{
System.out.println("MongoTemplate"+mongoTemplate);
return mongoTemplate.getCollection(collectionName);
}
#RequestMapping(value="/addU", method=RequestMethod.POST)
public #ResponseBody String add(#ModelAttribute("AddUser")User user, BindingResult result, ModelMap model)
{
String returnText="";
System.out.println("Inside response");
DBCollection table=getCollection("User");
BasicDBObject document = new BasicDBObject();
document.put("name", user.getName());
document.put("password", user.getPassword());
DBCursor cur = table.find(document);
if(cur.hasNext())
{
returnText="User Found Successfully";
}
else
{
returnText="User not Found";
}
return returnText;
}
}
Can anybody let me know the root cause of this error?
It looks as though you've missed the #Autowired annotation in your controller.
Try:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
#Autowired
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
Or autowire the field directly:
#Controller
public class LoginController {
#Autowired
private MongoTemplate mongoTemplate;

Why could <exclude-unlisted-classes>false</exclude-unlisted-classes> fail to work?

With this persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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_1_0.xsd"
version="1.0">
<persistence-unit name="ODP_Server_Test"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ODPServerDataSource)</non-jta-data-source> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:unit-testing;create=true" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.target-database" value="DERBY" />
</properties>
</persistence-unit>
</persistence>
and a simple test:
public class RepositoryTest {
private static Logger logger = LoggerFactory
.getLogger(RepositoryTest.class);
private static EntityManagerFactory emf;
private EntityManager em;
private RepositoryImpl repo = new RepositoryImpl();
#BeforeClass
public static void setUp() {
try {
logger.info("Starting in-memory DB for unit tests");
#SuppressWarnings("unused")
Class<?> cls = org.apache.derby.jdbc.EmbeddedDriver.class;
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;create=true").close();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during database startup.");
}
try {
logger.info("Building JPA EntityManager for unit tests");
emf = Persistence.createEntityManagerFactory("ODP_Server_Test");
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instantiation.");
}
}
#AfterClass
public static void tearDown() throws SQLException {
logger.info("Shutting down JPA");
if (emf != null) {
emf.close();
}
try {
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;drop=true").close();
} catch (SQLException ex) {
if (ex.getSQLState().equals("08006")) {
logger.info("DB shut down");
} else {
throw ex;
}
}
fail("DB didn't shut down");
}
#Before
public void setEM() {
em = emf.createEntityManager();
repo.setEntityManager(em);
}
#After
public void flushEM() {
if (em != null) {
em.flush();
em.close();
em = null;
}
}
#Test
public void noBlocksInEmptyDB() {
assertThat(repo.findFunBlock(1), is((FunctionalBlock) null));
}
}
I get
[EL Warning]: 2012-04-17 15:08:18.476--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
After replacing <exclude-unlisted-classes>false</exclude-unlisted-classes> with a lot of <class> elements, the problem can be fixed, but I'd prefer not to have to remember to edit persistence.xml every time I need to add a new entity or remove an old one. Why doesn't the version with <exclude-unlisted-classes> work?
I had faced similar situation
If I generate JPA metamodel, copy paste it in correct pacakge and check it in to svn, and disable metamodel generation, all junit tests were fine
if i generate metamodel with every build, at junit time - embedded glassfish will find all ejb and metamodel fine, but non ejb junit will fail
I had to do this in my src/test/resources/META-INF/persistence.xml
<persistence-unit name="test-xxx" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>file:../classes</jar-file>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.Oracle11Platform"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="JavaLogger"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:xxx"/>
<property name="javax.persistence.jdbc.password" value="xxx"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.user" value="xxx"/>
</properties>
</persistence-unit>