Hibernate Unknow Entity Exception after Spring/Hibernate Upgrade - spring

I did Spring upgrade from 3.x to 5.x and even Hibernate i got it upgraded to 5.x. Previously i was able to execute all the nativequeries using Hibernate JPA, but now the same piece of code is not working especially component-scan annotation (not instantiating beans anymore) after upgrade.
Below are the code snippets.
In Application context:
<context:component-scan base-package="com.flight.nh.domain" />
Bean class in com.flight.nh.domain package.
#Entity
#Table(name = "NOTIFICATION_ROLE")
public class NotificationRole implements Serializable {
}
Piece of code were below exception is thrown:
Caused by: org.hibernate.MappingException: Unknown entity: com.baxter.renal.nh.domain.NotificationRole
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:670) ~[hibernate-core-5.3.14.Final.jar:?]
Query query = this.entityManager.createNativeQuery(nativeSql.toString(), NotificationRole.class);
query.setParameter(INITIAL_VERSION, INITIAL_VERSION_VAL);
query.setParameter(USER_ID, userId);
query.setParameter(ROLE_LIST, roleIdList);
return query.getResultList();
Looks like NotificationRole bean could not be instantiated by spring leading to the exception as component-scan is not working as expected.
The same piece of code used to work with Spring 3.x. Can anyone please suggest how to proceed.

Related

Spring Boot JPA CrudRepository

I'm working with Spring Boot + Spring Data JPA and facing this problem when trying to inject a class that extends CrudRepository:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'topicRepository': Could not resolve
matching constructor (hint: specify index/type/name arguments for
simple parameters to avoid type ambiguities)
Repository Class:
public interface TopicRepository extends CrudRepository<Topic, Integer> {}
Service Class:
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
}
Any suggestions?
I was having the same issue, and I fixed it by switching Spring Boot versions. Changing the Spring Data JPA versions did nothing (this is where I assumed the bug would be), so I think there is a bug in Spring Boot version 1.5.1. I switched back to version 1.4.3 and the error was gone. I didn't try subsequent/different versions, so you may just have to experiment with your dependencies and their versions.
For the record, you can have your service class annotated with #Repository, it shouldn't make any difference. I've been setting these apps up the same way using the service/dao pattern, and it has never been too picky with the annotations. Hopefully this may help others whose Spring Boot development flow suddenly throws an error!
Which versions of spring-data-commons and spring-data-jpa are you using. I just ran into this using spring-data-commons 1.13.x with spring-data-jpa 1.10.x. Upgrading spring-data-jpa to 1.11.x fixed the issue for me.
I too had the same issue after updating Spring Boot to 1.5.4.
I am also using spring-data-envers, which was at version 1.0.4. Upgrading to 1.4.1 solved the problem.
I hope it helps someone :)
Make sure:
1) TopicRepository is annotated with #Repository.
2) You have the scanning packages configured:
<jpa:repositories base-package="mypkg.repositories"></jpa:repositories>
Had the same issue on 1.5.2. Upgrading to 1.5.5 solved the problem.
You can use Applicationcontext to inject repository to this reference topicRepository..
You just declare applicationcontext in #rest controller class
Same like topicRepository by using annotation. Then you pass this to the service class which should take parms through constructor.
Ex-
public TopicService(Applicationcontext ctx) {this.topicRepository =context.getBean(TopicRepository.class);
}

spring data for mongo Caused by: java.lang.AbstractMethodError

i use spring data to jpa and mongo.
dependency:
spring version is 4.0.2.RELEASE
spring-data-jpa version is 1.4.3.RELEASE
spring-data-mongodb version is 1.2.0.RELEASE
xml config:
<context:component-scan base-package="develop" />
<jpa:repositories base-package="develop.erp"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager" />
<mongo:repositories base-package="develop.doc" />
model:
#Document
public class OrderItem extends AbstractDocument {
enter code here
#Id
private BigInteger id;
private Integer orderNumber;
public get and set method ...
}
public interface IOrderItemDao extends PagingAndSortingRepository<OrderItem, BigInteger> {
List<OrderItem> findByOrderNumber(Integer number);
}
exception :
Caused by: java.lang.AbstractMethodError
at org.springframework.data.repository.query.Parameters.getBindableParameters(Parameters.java:235)
at org.springframework.data.repository.query.Parameters.assertEitherAllParamAnnotatedOrNone(Parameters.java:262)
at org.springframework.data.repository.query.Parameters.<init>(Parameters.java:85)
at org.springframework.data.mongodb.repository.query.MongoParameters.<init>(MongoParameters.java:47)
at org.springframework.data.mongodb.repository.query.MongoQueryMethod.createParameters(MongoQueryMethod.java:76)
at org.springframework.data.repository.query.QueryMethod.<init>(QueryMethod.java:70)
at org.springframework.data.mongodb.repository.query.MongoQueryMethod.<init>(MongoQueryMethod.java:62)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:119)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:304)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:161)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:162)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:44)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:144)
can someone have any idea ?
thanks very much..
In my case I had spring-data-solr(2.0.1) and spring-data-jpa(1.9.1) in my project. I noticed SolrQueryLookupStrategy was implementing QueryLookupStrategy interface from spring-data-commons which was transitively taken from spring-data-jpa jar. The problem was new solr was not compatible with old spring-data-jpa - signature of method in QueryLookupStrategy changed and code was not compiled correctly. Bumping spring-data-jpa to 1.10.1 solved the issue. I assume you have a similar problem. Track down where exception is thrown and search for compilation problems in spring jars.
This is due to incompatible version of spring-data and db-driver dependency. Please check if the version of db-driver is compatible with the provided spring-data dependency. I was facing the same issue, resolved by bumping the version of 'spring-data'.

reload in play framework 2.2 java giving exceptions when used with spring data jpa and hibernate

I am using Play Framework 2.2, Hibernate as JPA provider (4.2.8.Final), Spring (4.0.1.RELEASE) and Spring Data JPA (1.4.3.RELEASE).
I am using spring to instantiate to the controllers and using context:component-scan at the application load time to collect and configure all the required dependencies(repositories etc).
The way I have configured spring with play framework is
public class Global extends GlobalSettings {
private ApplicationContext applicationContext;
#Override
public void onStart(Application arg0) {
String configLocation = Play.application().configuration().getString("spring.context.location");
applicationContext = new ClassPathXmlApplicationContext(configLocation);
}
#Override
public <A> A getControllerInstance(Class<A> type) throws Exception {
return applicationContext.getBean(type);
}
}
and relevant section in application-context.xml is
Everything works extremely good when application loads for the first time. How ever as soon as I make any changes either in views or controllers and application reloads, Spring Data Jpa breaks and complains that my models are not of managed types.
Caused by: java.lang.IllegalArgumentException: Not an managed type: class models.User
Though it is not a problem in general, restarts works fine, I would really appreciate if someone can provide any inputs to reload the applicationContext completely on play reload.
I've had the same problem. Changing Spring Data JPA 1.4.3.RELEASE to 1.4.2.RELEASE solved it. I didn't have time to look further into the problem, so I don't know what is the cause.
This project is a good starting point: https://github.com/typesafehub/play-spring-data-jpa but it uses 1.3 version of Spring Data JPA.

JSF(MVC Framework) with Spring Dependency Injection Issue (Exception at Bean Creation)

i am using jsf2.0 as MVC framework and Spring just for Dependency Injection. i made it work but there is little problem when Spring Creating bean. Means on My JSFBean (ManagedBean) i have to use #Component Annotation of Spring otherwise i am not able to make it work. and because of that when my ManagedBean have some code in Constructor Spring is throwing Exception. It is working Perfect without Constructor CODE. Please comment if you need anything else.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean' defined in file [C:\Documents and Settings\KshiS\My Documents\NetBeansProjects\Sp_Js_1\build\web\WEB-INF\classes\com\ksh\excel\MyBean.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.ksh.excel.MyBean]: Constructor threw exception; nested exception is java.lang.NullPointerException
My JSF Bean code is
package com.ksh.excel;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* #author KshiS
*/
#ManagedBean
#ViewScoped
public class MyBean {
#Autowired
private Userdao userdao;
ArrayList<String> arrayList = new ArrayList<String>();
public MyBean()
{
Object object = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Userid");
if(object != null)
{
arrayList.add("Session Value");
}
else
{
arrayList.add("Temp Value");
}
}
public void print()
{
System.out.println(userdao.print());
}
}
How to Resolve it. ? OR Is there any possibility to Make it work without #Component Annotation on ManagedBean. ?
One More Important Question that I dont want use Spring As DI rather then i want use J2EE6 Dependency Injection. But also there is One problem That i have to use pure j2EE server like glassFish or JBOSS. Is it possible to use it in Tomcat. ? i know tomcat is not pure j2ee Server But i just want to use DI.
You need to post your full stacktrace here.
While your bean won't be injected using #AutoWired because your managed bean is not a spring managed bean (you need #ManagedProperty), that is not your primary problem.
The root cause is a failure in your bean's constructor. My guess would be that the following line is responsible for the NPE.
Object object = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Userid");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap() will only return a non-null SessionMap if there's a valid HttpSession. Your chained method call assumes that this will always be the case, and it appears that's not true here.
After you fix that code, you can then use #ManagedProperty to inject the spring bean into your JSF bean (you don't need Spring MVC here.)
Related reading:
JSF 2 inject Spring bean/service with #ManagedProperty and no xml
#ManagedProperty in a Spring managed bean is null
For the first problem try adding an #Lazy annotation to your JSF bean. That will delay the creation of the object till it is required. That will resolve the problem with the exception on startup - but I think it will not fix the issue. When used with JSF the object created by spring will not be used.
Take a look at the example in this article to do it correctly - using a spring variable resolver.
http://www.mkyong.com/jsf2/jsf-2-0-spring-integration-example/
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
On the second question - you can loook at TomEE. This article also has some details on using CDI in tomcat directly.

#Qualifier and #Resource doesn't work when running test case under Spring test framework

I have a test case which has a dependency of 'ticketDao', like below:
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
public class LfnSaleCancellationIntegrationTest extends BaseIntegrationTest {
//#Resource(name = "baseTicketDao")
private BaseTicketDao ticketDao;
....
public void setTicketDao(#Qualifier("baseTicketDao") BaseTicketDao ticketDao) {
this.ticketDao = ticketDao;
}
}
and BaseIntegrationTest extends from spring test framework's AbstractJpaTests, Spring is v3.0.5
When run this test case, I got a similar exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.mpos.lottery.te.gamespec.sale.dao.BaseTicketDao]
is defined: expected single matching bean but found 2:
[baseTicketDao, extraballTicketDao]
My project has evolved a long time, in fact when I encountered this exception at the first time, #Qualifier solved it. Till today this project has changed much, but I really have no idea why #Qaulifier and #Resource don't work any more.
And if i remove the dependency of 'ticketDao', the test case will pass. I am wondering whether there are some change of spring configuration cause this exception? or ... i have googled much, but seem no other people ever faced such a problem, pls give your comments, thanks very much!
You are using AbstractJPATests which is part of old spring test framework and (indirect) subclass of AbstractDependencyInjectionSpringContextTests. By default the injection is not annotation based but it discovers setters and fields and attempts injection by type. It would be recommended to switch to newer annotation based tests, refer to spring documentation for details.
As a workaround try to change autowire mode. Call it in test constructor as this.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME), rename your field to baseTicketDao and remove setter.
I knew the reason. In my new project, there are a statement of context:component-scan in spring configuration file, which will register 4 BeanPostProcessors by default:
AutowiredAnnotationBeanPostProcessor(#Autowired)
RequiredAnnotationBeanPostProcessor(#Require)
CommonAnnotationBeanPostProcessor(JSR-250 annotations, #Resource, #PostConstruct etc, #WebServiceRef )
PersistenceAnnotationBeanPostProcessor(#PersistenceUnit and #PersistenceContext)
While in my old project, only the default BeanPostProcessor(internalAutoProxyCreator) has been registered. My understanding is AutowiredAnnotationBeanPostProcessor will always wire by type. Anyway if remove context:component-scan, my test case can pass now.
In fact i have migrate all my test cases to spring test context framework now, and context:component-scan must be stated, otherwise #Autowired, #Resource etc annotation will be ignored, and you will get a great many of NullPointerException of those automaticaly injected dependencies.
NOTE: <context:annotation-config/> will register those 4 BeanPostProcessors too.

Resources