Spring-Boot Camel JPA auto configuration - jpa

there are a lot of examples of camel and spring dealing with JPA, but I would prefer spring boot autoconfigured data source instead of XML or configuration classes.
However even with
spring:
datasource:
url: jdbc:postgresql://postgres/fooBarBaz
username: fooBarBaz
password: fooBarBaz
jpa:
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
set up
The data source is not picked up:
No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as auto wire candidate for this dependency.

Related

Micronaut require entities during build

we created new application with JPA configuration. It is new application, so there are no entities yet and application failing during build with this error:
io.micronaut.context.exceptions.ConfigurationException: Entities not found for JPA configuration: 'default' within packages io.example.foo
This error is not error because there really no entity exists. When I created dummy entity to test, build pass. Can you tell me how to fix it?
This is my jpa configuration:
jpa:
default:
properties:
hibernate:
hbm2ddl:
auto: none
dialect: org.hibernate.dialect.PostgreSQL10Dialect
physical_naming_strategy: "io.micronaut.data.hibernate.naming.DefaultPhysicalNamingStrategy"
bytecode:
provider: none

Unable to run GraalVM native image with PostgreSQL and Hibernate

I am trying to build my service as GraalVM native image using Spring and buildpacks. My application is Spring Data REST app talking to PostgreSQL database. There is nothing unusual in the code. The image builds with no issues and runs outside of Docker container, but when I am trying to run the generated GraalVM container I am getting an error:
Description:
Native reflection configuration for org.hibernate.dialect.PostgreSQLDialect is missing.
The exception is
Caused by: java.lang.ClassNotFoundException: org.hibernate.dialect.PostgreSQLDialect
at com.oracle.svm.core.hub.ClassForNameSupport.forName(ClassForNameSupport.java:71) ~[na:na]
at java.lang.Class.forName(DynamicHub.java:1319) ~[.....:na]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130) ~[na:na]
My application.yml:
---
spring:
config:
activate:
on_profile: local
datasource:
url: jdbc:postgresql://localhost:5432/test
username: postgres
password: 1234
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
use-new-id-generator-mappings: false
ddl-auto: none
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
javax:
persistence:
validation:
mode: none
I know that Spring native image support still has issues, I am just wondering if the problem is on my side.
There now is a way to solve this for postgres with the current version of Spring Native using version spring native hints.
Native Hints
This turns out to be simple to implement using an annotation. See example below...
package com.margic.serverless.data;
import org.hibernate.dialect.PostgreSQL95Dialect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.nativex.hint.TypeHint;
#SpringBootApplication
#TypeHint(types = PostgreSQL95Dialect.class, typeNames = "org.hibernate.dialect.PostgreSQLDialect")
public class DataApplication {
public static void main(String[] args) {
SpringApplication.run(DataApplication.class, args);
}
}
The reason is Spring native support issues: The following dependencies are not known to work with Spring Native: ..., Rest Repositories, ...

Multiple datasources with Grails 3.1.5 and Postgresql

I am trying to connect to two postgresql databases from a single Grails 3.1.5 application, my application.yml looks like this:
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSources:
dataSource:
pooled: true
jmxExport: true
driverClassName: org.postgresql.Driver
username: username
password: password
dialect: net.kaleidos.hibernate.PostgresqlExtensionsDialect
dataSource_two:
pooled: true
jmxExport: true
driverClassName: org.postgresql.Driver
username: username
password: password
dialect: net.kaleidos.hibernate.PostgresqlExtensionsDialect
environments:
development:
dataSources:
dataSource:
dbCreate: update
url: jdbc:postgresql://localhost:5432/dbone
dataSource_two:
dbCreate: update
url: jdbc:postgresql://localhost:5432/dbtwo
test:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: update
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
I am getting this error and cannot start the application
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'transactionManager_dataSource_two' while setting constructor argument with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager_dataSource_two': Cannot resolve reference to bean 'sessionFactory_dataSource_two' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory_dataSource_two': Invocation of init method failed; nested exception is org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:140)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.grails.transaction.TransactionManagerPostProcessor.initialize(TransactionManagerPostProcessor.java:75)
at org.grails.transaction.TransactionManagerPostProcessor.setBeanFactory(TransactionManagerPostProcessor.java:53)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1565)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 20 common frames omitted
Looks like grails cannot find hibernate.cache.region.factory_class but as you can see I have that property in application.yml. I also checked if the class exists in classpath and it does. Any ideas why I am getting this error ?
the hibernate settings are datasource-specific, too.
so try adding a hibernate_two block with the hibernate settings for your dataSource_two
I updated the grails version to 3.1.9 and used the same exact configuration and it worked. The only thing I changed is was 'org.hibernate.cache.ehcache.EhCacheRegionFactory' to 'org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory'.

JAX RS 500 Error

I have a pretty simple service that is returning a 500 error - here's the details on the error:
[EL Info]: 2013-11-01 11:09:05.61--ServerSession(741529784)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Info]: 2013-11-01 11:09:06.452--ServerSession(741529784)--file:/C:/Users/Fred/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/cheese-ws/WEB-INF/lib/cheese-jpa.jar_cheese login successful
34442 [http-bio-8080-exec-1] ERROR org.apache.wink.server.internal.handlers.FlushResultHandler - The system could not find a javax.ws.rs.ext.MessageBodyWriter or a DataSourceProvider class for the java.util.Vector type and application/json mediaType. Ensure that a javax.ws.rs.ext.MessageBodyWriter exists in the JAX-RS application for the type and media type specified.
34446 [http-bio-8080-exec-1] INFO org.apache.wink.server.internal.RequestProcessor - The following error occurred during the invocation of the handlers chain: WebApplicationException (500 - Internal Server Error) with message 'null' while processing GET request sent to ...
The code is pretty straightforward and very similar to other services that work fine:
public class StudentTeacherCommunicationService extends BaseService {
#GET
#Path("classroomId/{classroomId}/studentId/{studentId}")
#Produces(MediaType.APPLICATION_JSON)
public List<ClassroomStudentCommunication> getCandidatesAsJson(#PathParam("classroomId") int classroomId, #PathParam("studentId") int studentId) {
EntityManager em = createEM();
TypedQuery<ClassroomStudentCommunication> query;
if(studentId==0) {
query = em.createQuery("SELECT csc FROM ClassroomStudentCommunication csc where csc.classroomId = :classroomId ORDER BY csc.threadOrder", ClassroomStudentCommunication.class);
query.setParameter("classroomId", classroomId);
List <ClassroomStudentCommunication> classCommunication = query.getResultList();
return classCommunication;
Any ideas?
This seems to be a Rest problem not a JPA problem.
If you happen to use Maven and generated the project with an archetype or IDE, it is worth to check the generated pom.xml. JSON support can be turned off by default in the pom.xml.
For example if you use Jersey and your project is generated with jersey-quickstart-webapp archetype then you should uncomment the following section manually in the pom.xml:
<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->

Spring data jpa: No property flush found for type void

I am using Spring Data JPA to develop a Spring MVC app. I built a JPA repository.
public interface AccessReportRepository extends JpaRepository<AccessReport, Long> {
}
I also use Spring Data Mongo along with JPA in my project.
When I run the project, I get this error.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lastDateController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.innolabmm.software.mongotest.springrest.ReadingService com.innolabmm.software.mongotest.springrest.LastDateController.readingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readingService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.innolabmm.software.mongotest.springrest.AccessReportRepository com.innolabmm.software.mongotest.springrest.ReadingService.reportRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accessReportRepository': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property flush found for type void
Does anyone have an idea what is going on? I am ready to provide more information if this will help solve the problem. Thanks in advance.
Are you using Spring Boot?
I had the same exception thrown when trying to use JPA and Mongo together, in a Spring Boot application. I found that the Repositories were always being interpreted by both JPA and Mongo, leading to problems as my repositories specifically extend JpaRepository.
I only wanted JPA repositories generated, so added the following to the Application entry point.
#EnableAutoConfiguration(exclude={MongoRepositoriesAutoConfiguration.class})
If you are using MongoDB with JPA (my JPA db is mysql) do this:
create separete packages for domain objects and for repositories (DAOs): i.e. demo.mysql.domain, demo.mysql.dao, demo.mongo.domain, demo.mongo.dao
in your configuration class use these annotations:
#EntityScan(basePackages={"demo.mysql.domain"})
#EnableJpaRepositories(basePackages={"demo.mysql.dao"})
#EnableMongoRepositories(basePackages={"demo.mongo.dao"})
annotate your JPA entities with #Entity and put them all in demo.mysql.domain package
annotate your MongoDB entities with #Document and put them all in demo.mongo.domain package
keep all of MongoDB reporitories in demo.mongo.dao package
keep all JPA repositories in demo.mysql.dao package
all mongo repositories should extend MongoRepository (i.e. public interface TransactionRepository extends MongoRepository)
all JPA repositories should extend JpaRepository (i.e. public interface CityRepository extends JpaRepository)
This is by far the easiest and the cleanest way that I have found (after digging through docs, btw.) to have MongoDB and Mysql working in one Spring Boot app.
That is what I have tried and what works. You could probably use MongoTemplate or extend CrudRepository instead of JpaRepository, or whatever else, try it, it might work.