No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available - spring

I use spring data jpa (using CrudRepository interface) in my project and have declared my repository interface like this :
/**
* Repository implementation {#link CrudRepository} for {#link Client} entity
* #author rsone.
*/
public interface ClientRepository extends CrudRepository<Client, Integer> {
}
And have my hibernate config like bellow :
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<context:component-scan base-package="com.rsone.mga.*" />
<jpa:repositories base-package="com.rsone.mga.repository" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="hibernateTransactionManager"/>
<bean id="datasource" parent="abstractDataSource">
<property name="dataSourceName" value="mgaDS" />
<property name="driverClass" value="${database.mga.jdbc.driver}" />
<property name="jdbcUrl" value="${database.mga.jdbc.url}" />
<property name="user" value="${database.mga.jdbc.user}" />
<property name="password" value="${database.mga.jdbc.pass}" />
<property name="preferredTestQuery" value="SELECT 1 FROM DUAL" />
</bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
<property name="fetchSize" value="5000" />
<property name="cacheQueries" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes>-->
<property name="packagesToScan" value="com.scor.mga.db"/>
</bean>
<!-- Enables the Hibernate #Transactional programming model -->
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<!--<property name="generateDdl" value="true"/>-->
<property name="database" value="SQL_SERVER"/>
</bean>
But When I try to run my project it give me that error (knowing that the base package of my repositories is com.rsone.mga.repository) :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
Edit
I use version 1.11.0.RELEASE of spring-data-jpa:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.0.RELEASE</version>
</dependency>

I had the same problem in my maven project.
So this below is not working
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
together with
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
Solution
It was solved by updating to the newest Spring boot release :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
Doing this already solved the problem.
It looks like the spring data tags are not backwards compatible with previous versions (other than the managed version).
So I would also recommend removing the version tag from the spring-data-cassandra dependency. Apparently Spring boot 1.5.1.RELEASE manages spring-data-cassandra 1.5.0.RELEASE.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
</dependency>

It doesn't seem to be an error in your configuration files.
It look like you have an #Autowired on a field of type java.lang.Class<org.springframework.data.repository.Repository<?, ?>> in one of the beans that are scanned.

Related

Spring 4 Hikari Connection Pool ClassCastException

I wish to use Hikari Connection Pool in my Spring 4 application. The database is Google Cloud SQL Postgres database.
I have the following dependency in pom.xml:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.1.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
In my applicationContext.xml, I have:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="org.postgresql.Driver" />
<property name="maximumPoolSize" value="10" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="url">jdbc:postgresql://google/mydatabase?cloudSqlInstance=projectId:regionName:myInstance&socketFactory=com.google.cloud.sql.postgres.SocketFactory</prop>
<prop key="user">postgres</prop>
<prop key="password">mypassword</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
But I'm getting the following exception:
Caused by: java.lang.ClassCastException: Cannot cast org.postgresql.Driver to javax.sql.DataSource
at java.lang.Class.cast(Class.java:3369)
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:102)
What could be going wrong?
The org.postgresql.jdbc.Driver is not a javax.sql.DataSource, it is a java.sql.Driver, so it doesn't work for the property dataSourceClassName as that property expects a javax.sql.DataSource class name.
If you want to use the driver (and not a DataSource), then you should use the property driverClassName.
So:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="driverClassName" value="org.postgresql.Driver" />
...
Use Hikari recommended datasource for PostgreSQL: org.postgresql.ds.PGSimpleDataSource
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
Database Driver DataSource class
PostgreSQL pgjdbc-ng com.impossibl.postgres.jdbc.PGDataSource
PostgreSQL PostgreSQL org.postgresql.ds.PGSimpleDataSource

Spring 4 Jpa Hibernate - Can't Inject EntityManager

I guess I have the same problem as many people, but unsolved on most of cases. I will try anyway, hope you guys can help me.
The problem is in my repository when I try to inject que Entity Manager using #persistenceContext annotation and always comes null.
The stack:
Spring 4.2.5
Spring Data 1.10.1
Hibernate 5
This is my xml for Sprint data:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="conquerPU"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="com.conquer.module" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/conquer" />
<property name="username" value="app" />
<property name="password" value="10203040" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<jpa:repositories base-package="com.conquer.module" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
This is my application context.xml
<context:annotation-config/>
<context:component-scan base-package="com">
<context:include-filter type="aspectj" expression="com.*" />
</context:component-scan>
<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="sessionData" class="com.conquer.common.SessionData" scope="session">
<aop:scoped-proxy/>
</bean>
<!--Hibernate persistence interceptor - Used for audit data-->
<bean id="hibernateInterceptor" class="com.conquer.module.security.interceptor.HibernateInterceptor"></bean>
<!--Application Context to be used anywhere-->
<bean id="applicationContextProvder" class="com.conquer.common.ApplicationContextProvider"/>
<!-- SpringMVC -->
<import resource="spring-mvc.xml"/>
<!-- SpringData -->
<import resource="spring-jpa.xml"/>
<!-- SpringSecurity -->
<import resource="spring-security.xml"/>
This is my repository
#Repository
#Transactional
public class BaseRepositoryImpl<T, ID extends Serializable> implements BaseRepository<T, ID> {
#PersistenceContext
public EntityManager em;
public RepositoryFactorySupport baseFactory;
public BaseRepository<T, ID> baseRepository;
public BaseRepositoryImpl() {
System.out.println("BASE REPOSITORY RUNNING...");
this.baseFactory = new JpaRepositoryFactory(em);
this.baseRepository = this.baseFactory.getRepository(BaseRepository.class);
}
// Implementations here ...
}
This is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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">
<persistence-unit name="conquerPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
<property name = "hibernate.show_sql" value = "true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.interceptor" value="com.conquer.module.security.interceptor.HibernateInterceptor"/>
</properties>
</persistence-unit>
</persistence>
Although this question is quite old, we faced with this problem as well and solved it by adding this bean to our application context:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
The documentation for context:annotation-config clearly states that this should not be necessary, but in our case it was (albeit we use Spring 4.2 inside Eclipse Virgo 3.7 with Gemini Blueprint, so this setup is probably far from mainstream).

Why won't spring autowire my test?

I've got the following spring configuration (actually, the configuration is more extensive, but I've included relevant parts):
testApplicationContext.xml
<!-- Business -->
<import resource="contexts/testBusinessContext.xml" />
<!-- Dao -->
<import resource="contexts/testDaoContext.xml" />
<!-- Persistence configuration -->
<import resource="contexts/testPersistenceContext.xml" />
<!-- Service actions -->
<import resource="contexts/testServiceActionContext.xml" />
testBusinessContext.xml
<bean id="basketBusiness" class="com.company.salesdataservice.business.BasketBusiness">
<property name="basketDao" ref="basketDao" />
<property name="tokenDao" ref="tokenDao" />
<property name="houseDao" ref="houseDao" />
<property name="currencyDao" ref="currencyDao" />
</bean>
testDaoContext.xml
<bean id="currencyDao" class="com.company.salesdataservice.dao.CurrencyDao">
<property name="dataSource" ref="companyDomainDataSource" />
</bean>
<bean id="houseDao" class="com.company.salesdataservice.dao.HouseDao"/>
<bean id="basketDao" class="com.company.salesdataservice.dao.BasketDao">
<property name="dataSource" ref="companyBookingDataSource" />
</bean>
<bean id="tokenDao" class="com.company.salesdataservice.dao.JavaRandomTokenDao" />
testPersistenceContext.xml
<bean id="companyBookingTransactionManager" class="com.company.utils.data.TransactionManager">
<property name="manager" ref="companyBookingSpringTransactionManager" />
</bean>
<bean id="companyBookingSpringTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="companyBookingDataSource" />
</bean>
<!-- initialised by a DataSourceInitializer. Left out for brevity. -->
<jdbc:embedded-database id="companyBookingDataSource" type="H2"/>
<!-- initialised by a DataSourceInitializer. Left out for brevity. -->
<jdbc:embedded-database id="companyDomainDataSource" type="H2"/>
testServiceActionContext.xml
<bean id="createBasketServiceAction" class="com.company.salesdataservice.serviceaction.CreateBasketServiceAction">
<property name="transactionManager" ref="companyBookingTransactionManager" />
<property name="basketBusiness" ref="basketBusiness" />
</bean>
I'm trying to autowire a field of the type CreateBasketServiceAction in one of my tests:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/testApplicationContext.xml"})
public class CreateBasketServiceActionTest {
#Autowired
CreateBasketServiceAction createBasketServiceAction;
}
However, Spring keeps telling me that it can't autowire:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.company.utils.data.serviceaction.TransactionalServiceAction] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
If i replace that field with a BasketBusiness basketBusiness field, then Spring is perfectly capable of doing it.
As far as I can see, both CreateBasketServiceAction and BasketBusiness is defined as a <bean /> in the XML configuration.
I've been banging my head against the wall for the past few hours on this. What am I doing wrong?

java.lang.ClassNotFoundException: org.hibernate.engine.SessionFactoryImplementor

i am trying to migrate to hibernate 4.1.0.Final with spring 3.1.1.RELEASE
and following is my configuration for hibernate:
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="${project.groupId}.domain" />
<!-- control the behavior of Hibernate at runtime,All are optional and
have reasonable default values -->
<property name="hibernateProperties">
<value>
<!-- hibernate.dialect: allows Hibernate to generate SQL optimized for
a particular relational database -->
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=create-drop
hibernate.show_sql=false
hibernate.jdbc.fetch_size=100
hibernate.jdbc.batch_size=100
hibernate.jdbc.batch_versioned_data=true
hibernate.order_inserts=true
hibernate.order_updates=true
hibernate.cache.use_query_cache=false
hibernate.cache.use_second_level_cache=false
</value>
</property>
</bean>
<!-- provides properties to hibernate to make it able to create session
factory. Hibernate uses instance of session bean of type -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<!-- responsible for creating sessionFactory opening transactions and binding
them to the current thread context. -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="nestedTransactionAllowed" value="true" />
</bean>
<!-- get exception translation from HibernateException into DataAccessException
hierarchy -->
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
but when trying to run the application, i got the following exception:
java.lang.ClassNotFoundException: org.hibernate.engine.SessionFactoryImplementor
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
please advise why i get this error, and how to fix it, thanks.
Try using the org.springframework.orm.hibernate4.HibernateTransactionManager
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>

spring eclipselink problem with IntegrityException

I try to use spring with eclipseLink and I've got an IntegrityException.
This is my configuration:
<?xml version="1.0" encoding="UTF-8"?>
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">
<import resource="data-source.xml" />
<tx:annotation-driven mode="proxy"
transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<!-- Entity manager -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="unit1" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
</property>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.DerbyPlatform" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> -->
<!-- <property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"
/> -->
<!-- <property name="showSql" value="true" /> -->
<!-- <property name="generateDdl" value="true" /> -->
<!-- </bean> -->
</property>
</bean>
<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
and exactly exception is:
[EL Config]: 2011-06-09 00:15:24.061--ServerSession(2050312009)--Connection(473155160)--Thread(Thread[main,5,main])--Connected: jdbc:derby://localhost:1527/springhib;create=true
User: app
Database: Apache Derby Version: 10.6.2.1 - (999685)
Driver: Apache Derby Network Client JDBC Driver Version: 10.7.1.1 - (1040133)
[EL Severe]: 2011-06-09 00:15:24.127--ServerSession(2050312009)--Thread(Thread[main,5,main])--Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Exception [EclipseLink-148] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The container policy [CollectionContainerPolicy(class org.eclipse.persistence.indirection.IndirectSet)] is not compatible with transparent indirection.
Mapping: org.eclipse.persistence.mappings.ManyToManyMapping[comments]
Descriptor: RelationalDescriptor(pl.adaknet.hibspring.domain.ArtEntity --> [DatabaseTable(ARTENTITY)])
but i don't have this problem when I use another Vendor
org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
any ideas?
Try to use this loadtimeweaver implementation:
package net.palesz.util;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
public class JpaAwareLoadTimeWeaver extends SimpleLoadTimeWeaver {
#Override
public ClassLoader getInstrumentableClassLoader() {
ClassLoader instrumentableClassLoader = super.getInstrumentableClassLoader();
if (instrumentableClassLoader.getClass().getName().endsWith("SimpleInstrumentableClassLoader")) {
return instrumentableClassLoader.getParent();
} else {
return instrumentableClassLoader;
}
}
}
Spring context.xml config:
<bean id="loadTimeWeaver" class="net.palesz.util.JpaAwareLoadTimeWeaver" />
An odd error because IndirectSet is valid. It seems to be a class loader issue, but I have not seen this in Spring before.
It could be related to your usage of loadTimeWeaver, so you could try removing that.
In what environment are you running Spring?
you have to use agent for dynamic weaving
-javaagent:spring-agent-2.5.6.jar
i had tried eclipseLink agent, but it didn't work.
more info about weaving for JPA on Spring:
http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch14s06.html
if you would like run your code on tomcat:
http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch14s06.html#orm-jpa-setup-lcemfb-tomcat

Resources