I'm trying to retrieve data from a MySQL database through Hibernate, but I'm stuck with this error:
Failed to create sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded
java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
[...]
I use a class called DAOFactory to get the hibernate session:
public class DAOFactory {
private static boolean isInstance = false;
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static Session session;
private DAOFactory() throws ExceptionInInitializerError{
if( !isInstance ) {
try {
Configuration cfg = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object."+ ex);
throw new ExceptionInInitializerError(ex);
}
session = sessionFactory.openSession();
isInstance = true ;
}
}
public static DAOFactory getInstance() {
return new DAOFactory() ;
}
public Session getSession() {
return session ;
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/enigma</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
And mysql-connector-java-5.1.26-bin.jar is already in the classpath:
Does anyone see what I'm missing ?
Thanks to Reimeus for the answer. mysql-connector-java-5.1.26-bin.jar needs to be in the runtime classpath.
Run -> Run Configurations... -> Classpath -> Add external JAR.
Clean everything, try again, and the Exception is gone.
For those who use Maven: add the following dependency in pom.xml.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
or choose another version from here.
Then you can get the artifact using:
mvn dependency:resolve
(if you don't use the IDE).
Faced the same issue with mysql-connector-java-5.1.48-bin.jar. To fix this issue I changed the driver class name from
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
to
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
In some cases it can be not a suitable solution to add jar to classpath via Run -> Run Configurations... -> Classpath -> Add external JAR.
First case
When the jar file cannot be put into classpath folder, there is alternative way to load class from the another place. You just need to instantiate URLClassLoader and then invoke loadClass() on it (was mentioned here):
URLClassLoader urlCL = new URLClassLoader(new URL[] {"path_to_jar"});
Class driverClass = urlCL.loadClass("com.mysql.jdbc.Driver");
Second case
If you would like to add your class to classpath at runtime (I prefer the answer of Ranjit Aneesh here), for this purpose you may create a very simple custom class loader extending URLClassLoader with the only overridden addUrl method:
public class DynamicURLClassLoader extends URLClassLoader {
public DynamicURLClassLoader(URLClassLoader classLoader) {
super(classLoader.getURLs());
}
#Override
public void addURL(URL url) {
super.addURL(url);
}
}
Then invoke it:
URLClassLoader urlCL = (URLClassLoader) ClassLoader.getSystemClassLoader();
new DynamicURLClassLoader(urlCL).addURL("path_to_jar");
Faced the same issue with mysql-connector-java-5.1.48-bin.jar. To fix this issue I changed the driver class name from
com.mysql.cj.jdbc.Driver
to
com.mysql.jdbc.Driver
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
<scope>provided</scope>
</dependency>
I had above dependency in Maven.
The scope tag had caused the error.
Removing scope tag solved the problem.
Download mysql-connector-java-8.0.20.jar
from https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.20/
Add the jar to class path
Run -> Run Configurations... -> Classpath -> Add external JAR.
Related
First, let me list the things I have used:
Eclipse JEE version 2021-03
Apache Tomcat Server 9
Hibernate ORM version 5.2.18.Final
PostgreSQL 14
Java 8
Some driver I have used: the required in lib of Hibernate ORM, postgresql-42.2.22.jar, jaxb-api-1.0.jar
Second is my code:
In the main class, I use it to run the application I let the name of class is CreateStudentDemo in the phucldh.Demo package in the src folder
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
Student tempStudent = new Student("Le", "Phuc", "phucldh.work#gmail.com");
// start a transaction
session.beginTransaction();
// save the student object
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Create student demo error: " + e.getMessage());
} finally {
factory.close();
}
}
And to connect to PostgreSQL I have a configuration file hibernate.cfg.xml in the src folder and the content of this file:
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/HibernateLearn</property>
<property name="connection.username">postgres</property>
<property name="connection.password">********</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
That all I have done but when I running I have a problem:
INFO: HHH000206: hibernate.properties not found
Exception in thread "main" java.lang.NoSuchMethodError: 'javax.xml.bind.JAXBContext javax.xml.bind.JAXBContext.newInstance(java.lang.Class[])'
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at phucldh.Demo.CreateStudentDemo.main(CreateStudentDemo.java:15)
And I see that line 15 of CreateStudentDemo.java is the line about
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
So I hope that anybody can help me find what I have wrong. Thank everybody very much. Hope all have a nice day.
I know that there are similar questions already, but the answers there didn't help me. So please would you mind to take a look at my particular question?
I am not very experienced with Hibernate yet and hava a problem when trying to create test data for my local database with Hibernate 4.3 and PostgreSQL.
I had another project where I did this exactly the same way and there it worked, so I did exactly the same setup but with another database, but now in my current project I get the following exception:
exception.DBException: Could not configure Hibernate!
at dao.BenutzerDAO.<init>(BenutzerDAO.java:48)
at export.ExportDBSchema.main(ExportDBSchema.java:16)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.postgresql.Driver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:245)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:200)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:156)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:95)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at dao.BenutzerDAO.<init>(BenutzerDAO.java:45)
... 1 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.postgresql.Driver
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242)
... 15 more
I searched for possible solutions, but none of them worked for me:
-)Specify Classpath to jar in Manifest.mf -> Did not work
-)Place the postgresql-9.4.1208.jre6.jar in lib folder under WEB-INF -> Did not work
-)Specify hibernate.cfg.xml file in Configuration().configure(); -> Did not work
I use Glassfish 4.1 and the org.postgres.Driver.class is existing, so why is it not found?
My hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Testdb</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="hibernate.connection.password">password</property>
<mapping class="entity.Benutzer"/>
</session-factory>
</hibernate-configuration>
Method in DAO class where the exception occurs:
try {
if (sessionFactory == null) {
Configuration conf = new Configuration().configure();
StandardServiceRegistryBuilder builder
= new StandardServiceRegistryBuilder();
builder.applySettings(conf.getProperties());
sessionFactory = conf.buildSessionFactory(builder.build());
}
} catch (Throwable ex) {
throw new DBException("Could not configure Hibernate!", ex);
}
I would be very thankful for every answer.
If you are using maven or gradle.
You can add this to ur pom.xml for maven
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.4</version>
</dependency>
And this for gradle
// https://mvnrepository.com/artifact/org.postgresql/postgresql
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.4'
You were close!
You need to place your postgresql-<version>.jar directly in the lib folder of your servlet container.
For instance, if you're working with Apache Tomcat, simply drop your jar under <TOMCAT_ROOT>/lib and you should be all set.
I am developing a Jersey application which is connected to a PostgreSQL database. I am looking for a solution how to configure Hibernate in a way that it always connects correctly to either the local or the Heroku based database (depending on if I deploy my application locally or if I push it to Heroku).
Using the Heroku guides, I tried something like this:
HibernateUtil.java:
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.setProperty("hibernate.connection.url",
System.getenv("DATABASE_URL"));
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':'
+ dbUri.getPort() + dbUri.getPath();
configuration
.setProperty("hibernate.connection.username", username);
configuration
.setProperty("hibernate.connection.password", password);
configuration.setProperty("hibernate.connection.url", dbUrl);
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} 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);
}
}
My hibernate.cfg.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 4.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/MYAPP</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Mapping with model class containing annotations -->
<mapping class="com.example.object" />
</session-factory>
</hibernate-configuration>
The idea is that HibernateUtil overrides the hibernate.cfg.xml properties (url, user, password). Deploying locally works but deploying to Heroku fails:
remote: [ERROR] Failed to execute goal de.juplo:hibernate4-maven-plugin:
.1.0:export (default) on project myapp: Execution default of goal de.juplo:hib
rnate4-maven-plugin:1.1.0:export failed: Error calling Driver#connect: Connecti
n to localhost:5432 refused. Check that the hostname and port are correct and t
at the postmaster is accepting TCP/IP connections. Connection refused -> [Help
]
It looks like on Heroku, your app is using the configuration from hibernate.cfg.xml instead of the buildSessionFactory() method. Can you confirm that the buildSessionFactory() is being called?
I think you should remove the hibernate.connection.* properties from your hibernate.cfg.xml and use DATABASE_URL locally. You can either set it in your env, or put it in a .env file and run your app locally with foreman start, which will pick this file up. This is the best way to ensure pairity between dev and prod environments, and it will test your buildSessionFactory() code.
You can even use the Heroku database locally if you desire by following this guide. Capture the Heroku DATABASE_URL and put it in your .env file. Then add the ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory args to the JDBC URL.
I'm facing some strange problem here and right now I'm stuck. I've read some other posts on this regards and some of then helped me to configure my enviroment, but for some reason that I couldn't find out why it is not working.
I need to place the hibernate.connection.url, hibernate.connection.username and hibernate.connection.password properties outside my WAR file to make easier to configure theese parameters when the system is deployed on different servers. So after digging over the Google I find this solution:
applicationContext.xml:
...
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="br.myapp.DataBaseConfig"/>
And the class DataBaseConfig
public class DataBaseConfig extends AnnotationSessionFactoryBean {
private final BaseConfig baseConfig = new BaseConfig();
public DataBaseConfig() {
super();
}
#Override
protected SessionFactory buildSessionFactory() throws Exception {
Properties dbConfig = new Properties();
dbConfig = baseConfig.getPropertiesFile("myPropertiesFile");
Configuration config = new Configuration();
Enumeration<Object> props = dbConfig.keys();
while ( props.hasMoreElements() ){
String key = (String)props.nextElement();
config.setProperty( key , dbConfig.getProperty(key) );
}
config.addResource("hibernate.cfg.xml");
SessionFactory sessionFactory = config.buildSessionFactory();
return sessionFactory;
}
}
And my hibernate.cfg.xml file looks like:
<hibernate-configuration>
<session-factory>
<mapping class="br.myapp.model.SomeClass1" />
<mapping class="br.myapp.model.SomeClass2" />
<mapping class="br.myapp.model.SomeClass3" />
</session-factory>
</hibernate-configuration>
My myPropertiesFile is:
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernate.connection.url=jdbc:oracle:thin:#localhost:1524:MyDB
hibernate.connection.username=user
hibernate.connection.password=passpass
hibernate.default_schema=myschema
hibernate.connection.oracle.jdbc.V8Compatible=true
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
#I'm usign c3p0 to pool connections
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=300
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=3000
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.EhCacheRegionFactory
With this enviroment when I'm trying to get something from the database without success on this way:
final SomeClass1 sm = repository.find(SomeClass1.class)
.where( Restrictions.eq( "someField" , varFromWebForm ) )
.uniqueResult();
But sm always returns null, and on the console there is no query printed even with hibernate.show_sql=true setted.
The strange thing is that when I change the configurations on my applicationContext.xml file like this
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation">
<value>classpath:/hibernate.cfg.xml</value>
</property>
</bean>
And the hibernate.cfg.xml file to this
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1524:MyDB</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">passpass</property>
<property name="hibernate.default_schema">myschema</property>
<property name="hibernate.connection.oracle.jdbc.V8Compatible">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<mapping class="br.myapp.model.SomeClass1" />
<mapping class="br.myapp.model.SomeClass2" />
<mapping class="br.myapp.model.SomeClass3" />
</session-factory>
</hibernate-configuration>
All works fine. So it is like the code that read the properties and inject it on the Configuration to Hibernate (DataBaseConfig) is not working properly.
Can someone point me out what am I doing wrong?
UPDATE:
There is no exceptions on the console. it just doesn't work.
UPDATE 2
This is the log from the apache server. I'm using VRaptor as controllerManager and the only things that appear when I call my method to do the query is the requisition to the controller nothing else, therefore I think that it is not important to put it here.
I've try to put the log here but the SO doesn't let me because it extrapolate the characters limit for a question so, here is a link to pastebin: http://pastebin.com/cASD7EPu
Thanks.
When you say (DataBaseConfig) is not working properly : Do you have somes Exceptions and a StackTrace returned by the Spring Container. Try To launch your app in debug/trace mode to see what happen exactly.
I've managed to solve my own question by changing the way I read the configurations. The waqy I was doing does not work and I couldn't find out why. Which is like this:
#Override
protected SessionFactory buildSessionFactory() throws Exception {
Properties dbConfig = new Properties();
dbConfig = baseConfig.getPropertiesFile("myPropertiesFile");
Configuration config = new Configuration();
Enumeration<Object> props = dbConfig.keys();
while ( props.hasMoreElements() ){
String key = (String)props.nextElement();
config.setProperty( key , dbConfig.getProperty(key) );
}
config.addResource("hibernate.cfg.xml");
SessionFactory sessionFactory = config.buildSessionFactory();
return sessionFactory;
}
So I was reading the Hibernate#Configuration docs and find the method configure(File file). Then I took the hibernate.cfg.xml out of my context and put it on my configs directory (which I get from a Util class of my project) and it work fine. The final method is like:
#Override
protected SessionFactory buildSessionFactory() throws Exception {
Configuration config = new Configuration();
config.configure(
new File( BaseConfig.CONFIG_BASE
+ File.separator
+ "hibernate.cfg.xml" )
);
SessionFactory sessionFactory = config.buildSessionFactory();
return sessionFactory;
}
And now it is working fine. I would like to find out why the previous configuration did not work to understand. This is not the best solution but solved my problem.
I've a friend here that always says: "It isn't an ugly solution until someone else show a better one!". So for now I will stick with this one.
Thanks to the ones who came here and tryied to help me.
I will not mark this answer as the right one for some time to see if someone else can show me a better solution :)
I have a problem with java jdk1.6.0_17 and hibernate .
I must open a hibernate session factory but mapping file (mapper-test.jar) is load by a personaly classLoader (URLClassLoader)
File map = new File("/opt/sigeco/infowebrepository/mapper/mapper-test.jar");
File map1 = new File("/opt/sigeco/infowebrepository/mapper/hibernate3.jar");
URL[] urls = new URL[] { map.toURI().toURL(),map1.toURI().toURL()};
URLClassLoader loader = new URLClassLoader(urls);
//test load is ok
loader.loadClass("it.sigeco.infoweb.dao.app.IcFabb");
Configuration configuration=new Configuration();
configuration.configure( loader.getResource("hibernate.cfg.xml"));
configuration.buildSessionFactory();
the problem is:
org.hibernate.MappingException: Resource: it/sigeco/infoweb/dao/app/IcFabb.hbm.xml not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:479)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1465)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1433)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1414)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1390)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1325)
at testLoad.main(testLoad.java:32)
the hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.jdbc.use_scrollable_resultset">true</property>
<mapping resource="it/sigeco/infoweb/dao/app/IcFabb.hbm.xml"/>
</session-factory>
</hibernate-configuration>
if load the mapper-test with build path is success, so the mapper-test is ok.
Seems that the Configuration search the file it/sigeco/infoweb/dao/app/IcFabb.hbm.xml in the system classloader and not in the URLClassLoader, but how do I connect the Configuration with the Loader?
Thank you
I've found one solution. I create a personaly ClassLoader, MapperClassLoader, that extend UrlClassLoader where in costructor:
MapperClassLoader(URL[] urls)
{
super( urls,MapperClassLoader.class.getClassLoader());
}
where urls contains the jars url. So set the parent loader whit the system class loader.
After create MapperClassLoader, set the system ClassLoader whit MapperClassLoader
Thread.currentThread().setContextClassLoader( MapperClassLoader.getInstance());
So the mapper-test.jar is usabile.