Hibernate configuration - java

I'm trying to get started with Hibernate, and when executing my program I get an error during initialization.
The exception is thrown by this class, copied from here:
package net.always_data.bastien_leonard;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here is the stacktrace:
> java net/always_data/bastien_leonard/Main
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.always_data.bastien_leonard.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at net.always_data.bastien_leonard.HibernateUtil.<clinit>(HibernateUtil.java:8)
at net.always_data.bastien_leonard.Main.main(Main.java:17)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration
at net.always_data.bastien_leonard.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 2 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:336)
... 3 more
I don't know where the problem comes from, so I don't really know where to look:
Problem of installation? This was handled by Maven, so I guess it's correct.
Hibernate can't find the configuration file?
Problem of classpath?
I'm invoking the program from the root of the classpath, which contains my hibernate.cfg.xml file.
Here is how it looks like in practice:
> pwd
/home/bastien/info/java/hibernate/test/Test/target/classes
> echo $CLASSPATH
/home/bastien/info/java/hibernate/test/Test/target/classes
> ls -F
hibernate.cfg.xml net/
> ls -FR
.:
hibernate.cfg.xml net/
./net:
always_data/
./net/always_data:
bastien_leonard/
./net/always_data/bastien_leonard:
Event.class Event.hbm.xml HibernateUtil.class Main.class
I've tried looking into the tutorial examples provided with Hibernate, but Maven can't compile them; it complains about missing artifacts.
By the way, Maven only lets me use Hibernate 3.3.1. Is it possible to use 3.3.2 and still let Maven handle the installation?

"java.lang.NoClassDefFoundError", indicating that the class loader can't find org.hibernate.cfg.Configuration says you've got a CLASSPATH problem.
echo $CLASSPATH
/home/bastien/info/java/hibernate/test/Test/target/classes
You've got to add all the Hibernate JARs and dependencies into the CLASSPATH as well. I don't see them in this echo.

Related

Bootstrap Hibernate SessionFactory in Netty/Armeria handler method fails with ClassNotFoundException

I have a Java Application that uses Armeria for a Web Service. When I create my Hibernate SessionFactory in the main method it works fine. But I am trying to create the SessionFactory when a certain Http Endpoint is called. In the handler method the session factory can not be created
Exception in thread "Thread-1" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Caused by: javax.xml.bind.JAXBException
- with linked exception:
[java.lang.ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:226)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:441)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 17 more
Caused by: java.lang.ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:577)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:224)
... 21 more
All I could find about this error is that JaxB is not provided for Java > 8 but i am using Java 8 and it works fine if I just create it at Application launch.
I believe it's some sort of class path conflict. In Java 8, the following code fails with ClassNotFoundException: com/sun/xml/bind/v2/ContextFactory, as reported in the question:
public class MyService {
#Get("/start")
public HttpResponse start() throws Exception {
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder().configure();
...
}
}
However, the problem goes away after upgrading to a newer Java version, such as Java 11.
Fortunately, the problem can be worked around by specifying the context class loader explicitly:
#Get("/start")
public HttpResponse start() throws Exception {
Thread.currentThread().setContextClassLoader(MyService.class.getClassLoader());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
final StandardServiceRegistryBuilder registryBuilder =
new StandardServiceRegistryBuilder().configure();
...
}

Flyway ClassNotFoundException: JavaUtilLogCreator

I'm using Flyway 5.2.4 and OSGI Bundle Activator. I want to migrate database on bundle Start() method.
Here's my ActivatorClass:
import org.flywaydb.core.Flyway;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private ServiceRegistration serviceRegistration;
public void start(BundleContext bundleContext) {
log.info("Starting...");
serviceRegistration = bundleContext.registerService(IConnector.class.getName(), new Connector(), null);
log.info("Started.");
//FlyWay Section
Flyway flyway = Flyway.configure().dataSource("jdbc:postgresql://localhost:5432/", "postgres", "12345").load();
flyway.migrate();
}
public void stop(BundleContext bundleContext) {
log.info("Stopping...");
serviceRegistration.unregister();
log.info("Stopped.");
}
}
As you can see, I'm using slf4j as my Logger. Maybe that's why I get this errors in my StackTrace after app deploying:
java.lang.Exception: Could not start bundle mvn:internship/db-connector/1.0.0 in feature(s) feature-1.0.0: Activator start error in bundle db-connector [2343].
at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:519)[20:org.apache.karaf.features.core:3.0.8]
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeatures(FeaturesServiceImpl.java:474)[20:org.apache.karaf.features.core:3.0.8]
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:415)[20:org.apache.karaf.features.core:3.0.8]
at Proxy683d032e_ad2c_4b9a_98f7_baca7b5564f1.installFeature(Unknown Source)[:]
at Proxyfff1bf4b_671e_4ff6_bb97_e0dabf9f20e8.installFeature(Unknown Source)[:]
at org.apache.karaf.kar.internal.KarServiceImpl.installFeatures(KarServiceImpl.java:282)[89:org.apache.karaf.kar.core:3.0.8]
at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:111)[89:org.apache.karaf.kar.core:3.0.8]
at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:93)[89:org.apache.karaf.kar.core:3.0.8]
at Proxy40d8d25a_37b2_4855_a381_fbb78daa68ce.install(Unknown Source)[:]
at Proxy068a2f57_120b_4ee8_b953_7c8262bae9a2.install(Unknown Source)[:]
at org.apache.karaf.deployer.kar.KarArtifactInstaller.update(KarArtifactInstaller.java:62)[91:org.apache.karaf.deployer.kar:3.0.8]
at Proxy3c143b4c_a2ef_49d0_870b_21a9b5f74704.update(Unknown Source)[:]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:1101)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:898)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:478)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
Caused by: org.osgi.framework.BundleException: Activator start error in bundle db-connector [2343].
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2196)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2064)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:942)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:516)[20:org.apache.karaf.features.core:3.0.8]
... 16 more
Caused by: java.lang.ExceptionInInitializerError
at org.flywaydb.core.internal.util.FeatureDetector.isSlf4jAvailable(FeatureDetector.java:96)
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:39)
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
at org.flywaydb.core.internal.util.FeatureDetector.<clinit>(FeatureDetector.java:25)
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:35)
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
at org.flywaydb.core.Flyway.<clinit>(Flyway.java:86)
at internship.connectors.postgresConnector.Activator.start(Activator.java:18)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2146)
... 20 more
Caused by: org.flywaydb.core.api.FlywayException: Unable to instantiate class org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator : org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:63)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:46)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.internal.util.ClassUtils.<clinit>(ClassUtils.java:39)[2348:org.flywaydb.core:5.2.4]
... 30 more
Caused by: java.lang.ClassNotFoundException: org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
at java.net.URLClassLoader.findClass(Unknown Source)[:1.8.0_212]
at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at java.lang.Class.forName0(Native Method)[:1.8.0_212]
at java.lang.Class.forName(Unknown Source)[:1.8.0_212]
at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:61)[2348:org.flywaydb.core:5.2.4]
... 33 more
So, I just have no idea what's wrong here, I've used simpliest example from official Flyway's site and get this errors.
I've already try to delete my own Logger. I thought it can let FlyWay to use it's logger, but everything goes the same way (same errors).
Could you help me?
P.S. Looks like this pull request somehow related to my problem.
Indeed it seems Flyway might have issues in OSGi. Maybe you can provide them an issue and your example.
Another issue with your example is that you try to access the DataSource via a url. This does not work in OSGi. The reason is that this way flyway has to have direct access to the database driver classes. This does not work in OSGi.
In OSGi the way to access a Database is with a DataSourceFactory which the database driver creates as a service. From this factory you can create a DataSource.
As not all database drivers offer this service there is pax-jdbc which provides factories for all common databases. It also allows to create a DataSource including pooling from a OSGi config.
Your approach of migrating on bundle start is a very bad idea. The methods in the activator must return quickly and a databse migration might take a while. Of course you want to make sure the migration takes place before any bundle in the system accesses the database. Fortunately there is a way to hook into the DataSource creation to do things like a migration.
See the liquibase tutorial which also shows a database migration. It uses the PreHook offered by pax-jdbc which makes sure your migration code is run before the DataSource is given to any other bundle.
I managed to avoid this error by setting a custom LogFactory before entering flyway's migration code. The basic idea is presented in this sample commit

Instantiating a hibernate Configuration throws error: Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

I am fairly new to the hibernate framework and I'm creating a simple application with a Udemy course. I've continually been getting a 'java.lang.NoClassDefFoundError' on the following stack. It appears that when I create a org.hibernate.cfg.Configuration object the exception is thrown. Any guidance would be appreciated on how to solve the following issue, is it possible that this hibernate version is buggy and I need to backtrack to a previous version?
Hibernate-Core Version: 5.3.0.Final
Hibernate-Annotations: 3.5.6.Final
My-SQL Server Version: 8.0.12
DEBUG - Logging Provider: org.jboss.logging.Log4jLoggerProvider
DEBUG - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
DEBUG - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
DEBUG - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:86)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:123)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)
at com.dataPack.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.dataPack.data.HibernateUtil.<clinit>(HibernateUtil.java:10)
at com.dataPack.data.Application.main(Application.java:9)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
... 7 more
Here is the HibernateUtil class I created to build the sessionFactory.
package com.dataPack.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
Configuration configuration = null;
try {
configuration = new Configuration();
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("Issue Building Session Factory!");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here is the hibernate.properties file we are suppose to use.
hibernate.connection.username=user
hibernate.connection.password=password
hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Since this project is known to work, it's likely that others have used a different Java version as the jaxb Apis were removed from Java SE. There are multiple ways to address this (as detailed in How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9 ) but the most reliable is to add the jaxb API dependency (groupId javax.xml.bind, artifactId jaxb-api -https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api/2.3.0) to the pom.xml or gradle build file.
Then rebuild and if you still hit ClassNotFound errors then see https://stackoverflow.com/a/43574427/9705485

How to deploy play framework 2.4 application on glassfish and read application.conf

I tried to deploy play framework 2.4 application on glassfish.
I used maven play2 plugin and made war file with the following instruction.
https://play2-maven-plugin.github.io/play2-maven-plugin/1.0.0-beta4/war-packaging.html
After that, I tried to deploy my war from glassfish console, but it returned the following error.
Error occurred during deployment: Exception while loading the app :
CDI deployment failure:Exception List with 3 exceptions:
Exception 0 : org.jboss.weld.exceptions.DeploymentException:
WELD-001408: Unsatisfied dependencies for type Environment with qualifiers #Default
at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject public play.api.db.BoneConnectionPool(Environment)
at play.api.db.BoneConnectionPool.<init>(BoneConnectionPool.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:370)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:291)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:165)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:529)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:515)
at org.jboss.weld.bootst .... msg.seeServerLog
Error occurred during deployment: Exception while loading the app :
CDI deployment failure:
WELD-001408: Unsatisfied dependencies for type Database with qualifiers #Default
at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject public modules.MyBatisModule$PlayDataSourceProvider(Database)
at modules.MyBatisModule$PlayDataSourceProvider.<init>(PlayDataSourceProvider.java:0) .
Please see server.log for more details.
And MyBatisModule is like this.
public class MyBatisModule extends org.mybatis.guice.MyBatisModule {
#Override
protected void initialize() {
environmentId("development");
bindConstant().annotatedWith(Names.named("mybatis.configuration.failFast")).to(true);
bindDataSourceProviderType(PlayDataSourceProvider.class);
bindTransactionFactoryType(JdbcTransactionFactory.class);
addMapperClasses();
}
#Singleton
public static class PlayDataSourceProvider implements Provider<DataSource> {
final Database db;
#Inject
public PlayDataSourceProvider(final Database db) {
this.db = db;
}
public DataSource get() {
return db.getDataSource();
}
}
I think the application can't read application.conf that containts DB setting. But I'm not sure.
Could you give me any advices?
Update 2015/01/13
I disabled "Implicit CDI" option on glassfish console when I deployed application.
I don't get the first error now, but I get another error...
Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException:
ContainerBase.addChild: start: org.apache.catalina.LifecycleException: com.google.inject.CreationException:
Unable to create injector, see the following errors:
1) Error in custom provider, Configuration error: Configuration error
[Cannot connect to database [default]] while locating play.api.db.DBApiProvider while locating play.api.db.DBApi for parameter 0
at play.db.DefaultDBApi.<init>(DefaultDBApi.java:28)
at play.db.DefaultDBApi.class(DefaultDBApi.java:28) while locating play.db.DefaultDBApi while locating play.db.DBApi for field
at play.db.DBModule$NamedDatabaseProvider.dbApi(DBModule.java:61) while locating play.db.DBModule$NamedDatabaseProvider
at com.google.inject.util.Providers$GuicifiedProviderWithDependencies.initialize(Providers.java:149)
at play.db.DBModule.bindings(DBModule.java:40): Binding(interface play.db.Database qualified with QualifierInstanc .... msg.seeServerLog
My conf/application.conf is here:
db.default.driver=oracle.jdbc.driver.OracleDriver
db.default.url="jdbc:oracle:thin:#url..."
db.default.username=username
db.default.password=password
And it works on local environment.
I think glassfish can't read application.conf in war file.
I'm sorry. Could you give me the advice again?
Update 2015/01/14
The following is the part of full log.
Caused by: Configuration error: Configuration error[Exception during pool initialization]
at play.api.Configuration$.configError(Configuration.scala:178)
at play.api.PlayConfig.reportError(Configuration.scala:1048)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:69)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:124)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:122)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:143)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:139)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:44)
... 130 more
Caused by: com.zaxxer.hikari.pool.PoolInitializationException: Exception during pool initialization
at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:542)
at com.zaxxer.hikari.pool.BaseHikariPool.<init>(BaseHikariPool.java:171)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:60)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:48)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:80)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:58)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:54)
at scala.util.Try$.apply(Try.scala:191)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:54)
... 136 more
Caused by: java.sql.SQLException: JDBC4 Connection.isValid() method not supported, connection test query must be configured
at com.zaxxer.hikari.pool.BaseHikariPool.addConnection(BaseHikariPool.java:441)
at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:540)
... 144 more
3) Error in custom provider, java.lang.NullPointerException
at play.db.DBModule.bindings(DBModule.java:40):
Binding(interface play.db.Database qualified with QualifierInstance(#play.db.NamedDatabase(value=default)) to ProviderTarget(play.db.DBModule$NamedDatabaseProvider#34850279)) (vi
a modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
while locating play.db.Database annotated with #play.db.NamedDatabase(value=default)
Some thoughts (it should be comment, but I cannot write comments on SO yet).
If your application.conf file is inside WEB-INF/classes directory, it should be found (more info - https://www.playframework.com/documentation/2.4.x/ProductionConfiguration#Specifying-an-alternate-configuration-file).
Does war file contain JDBC driver?
Maybe you should configure JNDI - https://www.playframework.com/documentation/2.4.x/ScalaDatabaseOthers#Exposing-the-datasource-through-JNDI
My problem cause is that:
Caused by: java.sql.SQLException: JDBC4 Connection.isValid() method not supported, connection test query must be configured
https://www.playframework.com/documentation/2.4.x/Migration24#JDBC-connection-pool
After I add the following setting on application.conf, it works.
(This sql is for Oracle DB.)
db.default.hikaricp.connectionTestQuery="SELECT 1 FROM DUAL"
Thank you for your help!

Map Entities loaded dynamically from external jars or outside classpath

I need to map Entities that are not listed at hibernate.cfg.xml, those classes are loaded dynamically
from an arbitraty folder. I'm trying to register a ClassLoaderService to change the loading behavior, the
following code runs fine if the classes are defined at compile time and exist in the classpath, but if
I try to map a dinamically loaded class I get ClassNotFoundException. There are some questions about the same issue, but I didn't find any working solution.
URL file = ConsultaBase.class.getProtectionDomain().getCodeSource().getLocation().toURI().resolve("implementacao/").resolve("hibernate.cfg.xml").toURL();
Configuration configuration = new Configuration()
.addAnnotatedClass(Registro.class).configure(file);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder (
new BootstrapServiceRegistryImpl(
new ClassLoaderServicePirilampo(Registro.class.getClassLoader()),
new LinkedHashSet<Integrator>()
)
)
.applySettings(configuration.getProperties())
.addService(ClassLoaderService.class, new ClassLoaderServicePirilampo())
.build();
//this line throws ClassNotFoundException
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
I extended the ClassLoaderServiceImpl in order to log the requested classes, and noticed that running from JUnit, from the project where the classes are defined, it works fine, I get the class loading log from the Service. But the Service never receives
the request for the same class if I addAnnotatedClass that was loaded dinamically (from GroovyClassLoader).
The last line throws de folowing error:
17:06:49 ERROR [AssertionFailure] HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): java.lang.ClassNotFoundException: implementacao.Registro
PersistentClass name cannot be converted into a Class
org.hibernate.AssertionFailure: PersistentClass name cannot be converted into a Class
at org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId(BinderHelper.java:817)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:2169)
at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:963)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:796)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at implementacao.ConsultaBase.createSessionFactory(ConsultaBase.java:64)
at implementacao.ConsultaBase.consultar(ConsultaBase.java:92)
at implementacao.ConsultaBase$consultar.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at ConsultaBaseConector.run(ConsultaBaseConector.groovy:6)
at groovy.util.GroovyScriptEngine.run(GroovyScriptEngine.java:551)
at br.org.fplf.processo.maquinaexecucao.parser.ParserAtividadeAutomatica.executar(ParserAtividadeAutomatica.java:43)
at br.org.fplf.processo.maquinaexecucao.MaquinaExecucao.executarAtividadeAutomatica(MaquinaExecucao.java:1050)
at br.org.fplf.processo.maquinaexecucao.MaquinaExecucao.executarAtividadeFluxo(MaquinaExecucao.java:973)
at br.org.fplf.processo.maquinaexecucao.MaquinaExecucao.executar(MaquinaExecucao.java:646)
at br.org.fplf.processo.maquinaexecucao.MaquinaExecucao.run(MaquinaExecucao.java:368)
Caused by: java.lang.ClassNotFoundException: implementacao.Registro
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.annotations.common.util.ReflectHelper.classForName(ReflectHelper.java:60)
at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.classForName(JavaReflectionManager.java:138)
at org.hibernate.cfg.BinderHelper.getPropertyOverriddenByMapperOrMapsId(BinderHelper.java:813)
... 20 more
This worked for me:
Thread.currentThread().setContextClassLoader(DynamicallyLoadedClass.getClassLoader());
example:
URL file = ConsultaBase.class.getProtectionDomain().getCodeSource().getLocation()
.toURI().resolve("hibernate.cfg.xml").toURL();
Configuration configuration = new Configuration()
.addAnnotatedClass(Registro.class).configure(file);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
Thread.currentThread().setContextClassLoader(Registro.class.getClassLoader());
sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Categories