How to fix mapping not found exception for Hibernate 5? - java

Hello I am new in hibernate and at the moment I'm trying to do something in practice. But have some errors.
I try to use hibernate in my project. I read the tutorial and start to integrate Hibernate into my java maven project.
So first of all I added the next dependencies:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.6.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
The next step was to add hibernate.cfg.xml file into the src/main/resources directory. This file looks like:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/testprojectdatabase</property>
<property name="hibernate.connection.username">username_here</property>
<property name="hibernate.connection.password">password_here</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</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>
<mapping resource="milkiv/mytestproject/models/UserInfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Then I create UserInfo.java for mapping user_info table and put it inside src/main/java/milkiv/mytestproject/models/UserInfo.java, and UserInfo.hbm.xml file which I put inside src/main/resources/milkiv/mytestproject/models/UserInfo.hbm.xml.
I have also created the class UserInfoManager which look like:
public class UserInfoManager implements ManagerAdd<UserInfo> {
private final SessionFactory factory;
public UserInfoManager() {
factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
public int add(UserInfo user) {
Transaction transaction = null;
Integer userId = null;
try (Session session = factory.openSession()){
transaction = session.beginTransaction();
userId = (Integer) session.save(user);
transaction.commit();
} catch (HibernateException he) {
if (transaction != null) {
transaction.rollback();
}
}
return userId;
}
}
When I try to create test for method add(UserInfo user) it failed on UserInfoManager constructor on factory initialization because of
Mapping (RESOURCE) not found : milkiv/mytestproject/models/UserInfo.hbm.xml : origin(milkiv/mytestproject/models/UserInfo.hbm.xml)
So eventually I know where, but do not know how to fix this. I have read a lot of answers for this questions on stackoverflow but no one didn't help me to fix this error.
I will appreciate any ideas, help and explanation how to fix this problem...
full stack trace:
Mapping (RESOURCE) not found : milkiv/mytestproject/models/UserInfo.hbm.xml : origin(milkiv/mytestproject/models/UserInfo.hbm.xml)
org.hibernate.boot.MappingNotFoundException
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.cfgxml.spi.MappingReference.apply(MappingReference.java:70)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:413)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at milkiv.mytestproject.managers.UserInfoManager.(UserInfoManager.java:22)
at milkiv.mytestproject.managers.UserInfoManagerTest.testAdd(UserInfoManagerTest.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
UPDATE
If anyone need, solving is in the comments for #v.ladynev answer.

I check your approach and everything works fine.
When you put UserInfo.hbm.xml in the src/main/resources/milkiv/mytestproject/models/UserInfo.hbm.xml
it will appear in the
bin/milkiv/mytestproject/models/UserInfo.hbm.xml
after build (instead of bin can be your build folder).
So /milkiv/mytestproject/models/ looks like as other source packages in the build folder. Please, check it. Check that you have resource folder in the classpath.
Try to add / in the beginning
<mapping resource="/milkiv/mytestproject/models/UserInfo.hbm.xml"/>
Update
Adding / in the beginning doesn't matter, because of Hibernate remove it before loading by ClassLoader. So the most valid way — without / in the beginning.
Try to put UserInfo.hbm.xml in the root of resources
<mapping resource="UserInfo.hbm.xml"/>
Update
Try to test
public UserInfoManager() {
System.out.println(UserInfoManager.class
.getResource("/milkiv/mytestproject/models/UserInfo.hbm.xml"));
System.out.println(ClassLoader.getSystemClassLoader().getResource(
"milkiv/mytestproject/models/UserInfo.hbm.xml"));
}
Note leading / in the first case. What console output after
new UserInfoManager();

#NickolasUA you are using Hibernate 5.
So change the last line in hibernate.cfg.xml
<mapping class="milkiv.mytestproject.models.UserInfo.hbm.xml"/>

Related

hibernate error on hibernate.cfg.xml

i get this error when i try to start compiling my project
dic 27, 2017 11:55:50 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
dic 27, 2017 11:55:50 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Initial SessionFactory creation
failed.org.hibernate.internal.util.config.ConfigurationException: Unable to
perform unmarshalling at line number 0 and column 0 in RESOURCE
hibernate.cfg.xml. Message: null
Exception in thread "main" java.lang.ExceptionInInitializerError
at progetto1java.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
at progetto1java.HibernateUtil.<clinit>(HibernateUtil.java:8)
at progetto1java.Gestore_Utenti.VerificaUtente(Gestore_Utenti.java:59)
at progetto1java.Sistema.main(Sistema.java:48)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable
to perform unmarshalling at line number 0 and column 0 in RESOURCE
hibernate.cfg.xml. Message: null
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
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 org.hibernate.cfg.Configuration.configure(Configuration.java:244)
at progetto1java.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
... 3 more
Caused by: javax.xml.bind.JAXBException
- with linked exception:
[java.lang.ClassNotFoundException:
com.sun.xml.internal.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 9 more
Caused by: java.lang.ClassNotFoundException:
com.sun.xml.internal.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
... 13 more
i look carefully my configuration file but i don't now what's the problem..
these are in order my configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sistema_musicale</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="progetto1java.Utente"/>
<mapping class="progetto1java.Brano"/>
</session-factory>
</hibernate-configuration>
and hibernate class util.
class hibernate to create session
sorry for my using of image instead of code but i had indentation problem...
I just resolved an
failed.org.hibernate.internal.util.config.ConfigurationException: Unable to
perform unmarshalling at line number 0 and column 0 in RESOURCE
hibernate.cfg.xml.
error building my own app.
The solution was actually very simple, namely I was missing dependencies in my pom.xml file. I had just one:
...
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
...
Adding the three below solved the problem:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
I hope this will help someone.
Please ensure that your "hibernate.cfg.xml" file is present in the "src" folder of your project.

Hibernate gives error error as "Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set" when there is no internet connection

Hibernate works fine when there is internet connection. But when there is no internet connection, it gives me
Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
error. I think my application is trying to access the internet connectivity when running. The detail error that I get is given below:-
Dec 22, 2015 6:17:43 PM
org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator
initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to
DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.pos.admin.admin_module.admin_module.hibernatefiles.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:32)
at com.pos.admin.admin_module.admin_module.hibernatefiles.hibernate.HibernateUtil.getSessionFactory(HibernateUtil.java:44)
at com.pos.admin.admin_module.main.AdminModule.start(AdminModule.java:21)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(Unknown
Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(Unknown
Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(Unknown
Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(Unknown
Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown
Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown
Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown
Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(Unknown
Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
at com.pos.admin.admin_module.admin_module.hibernatefiles.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:39)
at com.pos.admin.admin_module.admin_module.hibernatefiles.hibernate.HibernateUtil.getSessionFactory(HibernateUtil.java:44)
at com.pos.admin.admin_module.main.AdminModule.start(AdminModule.java:21)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(Unknown
Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(Unknown
Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(Unknown
Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(Unknown
Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
... 1 more
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.pos.admin.admin_module.admin_module.hibernatefiles.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.java:32)
... 11 more
Exception running application com.pos.admin.admin_module.main.AdminModule
My pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pos.admin.admin_module</groupId>
<artifactId>admin_module</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>admin_module</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.5.Final</version>
</dependency> -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version> </dependency> -->
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</version> </dependency> -->
<!-- <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId>
<version>2.2.4</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId> <version>2.2.4</version> </dependency> -->
</dependencies>
</project>
My hibernate configuration (hibernate.cfg.xml) file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/point_of_sales</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">
</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<!--
<property name="hbm2ddl.auto">update</property> -->
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.Category"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.ProductHeader"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.PurchaseDetail"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.PurchaseHeader"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.SalesDetail"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.SalesHeader"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.Settings"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.Unit"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.User"/>
<mapping class="com.pos.admin.admin_module.hibernatefiles.dto.Supplier"/>
<!-- <mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.Supplier"/>
<mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.PurchaseHeader"/>
<mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.ProductHeader"/>
<mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.Category"/>
<mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.Unit"/> -->
<!-- <mapping class="com.pos.storekeeper.storekeeper_module.hibernateFiles.dto.User"/> -->
<!-- <mapping class="com.pos.admin.admin_module.admin_module.main.Cart1"/> -->
</session-factory>
</hibernate-configuration>
HibernateUtil class where I create Configuration and Session objects
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
try{
configuration.configure("hibernate.cfg.xml");
}catch(Exception e){
System.out.println("Exception while handling configureation file :" + e.getMessage());
System.out.println("asfsdaf " + configuration);
}
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) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static void closeSessionFactory(){
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
I want to fix this issue because internet connectivity cannot be always available. Thank you
to use hibernate offline you will have to change your dtd in your xml mapping and configuration files.make sure hibernate jar is in your classpath
for xml mapping file
<!DOCTYPE hibernate-mapping SYSTEM
"classpath://org/hibernate/hibernate-mapping-3.0.dtd">
for configuration file :
<!DOCTYPE hibernate-configuration SYSTEM
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
http://www.journaldev.com/2959/how-to-configure-hibernate-cfg-xml-to-work-offline
Try to remove SessionFactory from this:
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
To be:
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Or add this buildSessionFactory() like this:
private static SessionFactory sessionFactory = buildSessionFactory();
Your version of Hibernate has the ability to auto-configuring the Dialect, once its been able to establish a JDBC connection. If you can't establish a JDBC connection, that might be the problem.

Openshift Unable to locate persistence units

I'm developing Hibernate JPA persistance web application, with my persistence.xml in src/main/resources/META-INF/persistence.xml (in war file it's in WEB-INF/classes/META-INF). It all works well on local Tomcat server, but when put on Openshift JBoss EWS, getting this message on startup:
Caused by: javax.persistence.PersistenceException: Unable to locate persistence units
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:101)
at org.hibernate.ejb.HibernatePersistence.getEntityManagerFactoryBuilderOrNull(HibernatePersistence.java:93)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:88)
at org.hibernate.ejb.HibernatePersistence.getEntityManagerFactoryBuilderOrNull(HibernatePersistence.java:101)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:69)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at komante.server.SpringConfig.devEntityManagerFactory(SpringConfig.java:29)
at komante.server.SpringConfig$$EnhancerBySpringCGLIB$$17e4a4c6.CGLIB$devEntityManagerFactory$1()
at komante.server.SpringConfig$$EnhancerBySpringCGLIB$$17e4a4c6$$FastClassBySpringCGLIB$$55fcba01.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at komante.server.SpringConfig$$EnhancerBySpringCGLIB$$17e4a4c6.devEntityManagerFactory()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 28 more
Caused by: java.util.MissingResourceException: Could not load any resource bundle by com.sun.org.apache.xerces.internal.impl.msg.XMLSchemaMessages
at com.sun.org.apache.xerces.internal.utils.SecuritySupport$7.run(SecuritySupport.java:174)
at com.sun.org.apache.xerces.internal.utils.SecuritySupport$7.run(SecuritySupport.java:166)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.org.apache.xerces.internal.utils.SecuritySupport.getResourceBundle(SecuritySupport.java:166)
at com.sun.org.apache.xerces.internal.impl.xs.XSMessageFormatter.formatMessage(XSMessageFormatter.java:70)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:398)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4162)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(XSDHandler.java:4145)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDAbstractTraverser.reportSchemaError(XSDAbstractTraverser.java:721)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDSimpleTypeTraverser.getSimpleType(XSDSimpleTypeTraverser.java:406)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDSimpleTypeTraverser.traverseSimpleTypeDecl(XSDSimpleTypeTraverser.java:163)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDSimpleTypeTraverser.traverseGlobal(XSDSimpleTypeTraverser.java:104)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.traverseSchemas(XSDHandler.java:1442)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:630)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:617)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:575)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:541)
at com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory.newSchema(XMLSchemaFactory.java:252)
at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:627)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.resolveLocalSchema(PersistenceXmlParser.java:435)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.v21Schema(PersistenceXmlParser.java:400)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.validate(PersistenceXmlParser.java:347)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.loadUrl(PersistenceXmlParser.java:310)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.parsePersistenceXml(PersistenceXmlParser.java:114)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.doResolve(PersistenceXmlParser.java:104)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.locatePersistenceUnits(PersistenceXmlParser.java:86)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:97)
Persistence.xml starts with
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
and has two persistence units in it. I alse deleted hibernate.cfg.xml, both things suggested in other SO answers. Anyone know what I'm doing wrong here?
Got it.
The problem was I used Persistence.createEntityManagerFactory("unit") to create EntityManagerFactory and injected it in other Spring beans.
Now I put
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="unit" />
</bean>
directly in applicationContext.xml.
Still doesn't explain what was wrong with previous approach, but it works.

JUnit, JPA, Hibernate and Postgres: How to test?

I've been stuck for a while now. I have searched a lot and I can't find the easiest way to test entity classes or JPA operations against a postgres database. I've found how to using Spring, Mockito and other things, but I can't find the simplest way using pure Java.
I have the following JUnit test:
public class ModelConverterTest {
private static EntityManagerFactory emf;
private static EntityManager em;
public ModelConverterTest() {
}
#BeforeClass
public static void setUpClass() throws Exception {
emf = Persistence.createEntityManagerFactory("PU");
em = emf.createEntityManager(); // Retrieve an application managed entity manager
}
#AfterClass
public static void tearDownClass() throws Exception {
em.close();
emf.close(); //close at application end
}
#Before
public void setUp() {
...
}
#After
public void tearDown() {
}
/**
* Test of SIMModelToModel method, of class ModelConverter.
*/
#Test
public void testSIMModelToModel() {
System.out.println("SIMModelToModel");
SIMModel simModel = new PESMModel();
simModel.addState(testState);
Model expResult = null;
Model result = ModelConverter.SIMModelToModel(em, simModel);
assertTrue(expResult!=null);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
}
and when running it, I get the following error:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/PersistenceContextType
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:787)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:447)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getDeclaredMethods(Class.java:1808)
at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:104)
at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:101)
at java.security.AccessController.doPrivileged(Native Method)
at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:100)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:84)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:221)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
at java.lang.reflect.Field.declaredAnnotations(Field.java:1033)
at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1026)
at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:196)
at org.junit.runners.model.FrameworkField.getAnnotations(FrameworkField.java:26)
at org.junit.runners.model.TestClass.addToAnnotationLists(TestClass.java:52)
at org.junit.runners.model.TestClass.<init>(TestClass.java:45)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
My persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="PU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/modelsystemdb</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
What should I do to make the test run?
Quoting Trouble With Crippled Java EE 6 APIs in Maven Repository And The Solution by Adam Bien:
Instead of using
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
You should use alternative (geronimo, jboss etc.) dependencies:
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-ejb_3.1_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_2.0_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
Had a similar issue. i.e Even though the Hibernate JPA jar was available through transitive dependencies and javaee 6.0 dependency was provided, the JUNIT Test case was failing. I just moved the javaee dependency at the end of the dependencies definition on the pom file so that the hibernate JPA api jar appeared before the Javaee jar during classpath resolution. That seemed to do the trick and I was able to run the test case. Hope this helps.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
javaee appears after hibernate dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
If you want to use JPA in your tests, then you will need to have a JPA provider on the classpath when you run them. You can compile against javaee-api, but you must have a real, live provider at runtime.
You mention that you're using GlassFish; that uses EclipseLink as its provider, so it would make sense for you to do the same for your tests. There's information about using EclipseLink via Maven on their wiki.
We a very similar issue: Junit tests were successfully executing during maven build, however trying to run them from Eclipse directly showed this awful "Absent Code" error. The solution is not in pom.xml-s (they must be right since your build runs, right?) but the configuration of Junit execution in eclipse. In our case, when the maven dependencies were moved on top of the project itself, the correct implementation (eclipselink 2.0.4) persistence classes were loaded. So in eclipse try to check "Run Configurations...", select the Junit configuration in question and on the "Classpath" tab, change the order of libraries in the "User Entries" section: move Maven dependencies on top.
Best regards,
Joe Public
In my case under Run Configurations/ClassPath on the the project, click Edit and check "Only include exported entries" that did the trick.

Why can't I test my project using JUnit 4?

I am using Spring 3, Hibernate 3 in my project. But I can not test it using JUnit 4.
Here is my Test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})
public class UserDaoTestCase extends AbstractJUnit4SpringContextTests {
#Autowired
private UserDao userDao;
#Test
public void testSimple() {
// do some tests...
}
// setters and getters
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
I run this test, and I always get this exception:
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at
org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in URL
[file:WebRoot/WEB-INF/applicationContext.xml]: Invocation of init
method failed; nested exception is org.hibernate.HibernateException:
Unable to get the default Bean Validation factory at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at
org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at
org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at
org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
at
org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
... 24 more Caused by: org.hibernate.HibernateException: Unable to
get the default Bean Validation factory at
org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:127)
at
org.hibernate.cfg.Configuration.applyBeanValidationConstraintsOnDDL(Configuration.java:1704)
at
org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1654)
at
org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445)
at
org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
at
org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at
org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
... 37 more Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:118)
... 45 more Caused by: org.hibernate.HibernateException: Unable to
build the default ValidatorFactory at
org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:383)
at
org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:109)
... 50 more Caused by: javax.validation.ValidationException: Unable
to instantiate Configuration. at
javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:272)
at
javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
at
org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:380)
... 51 more Caused by: java.lang.NullPointerException at
java.util.ResourceBundle.getBundle(ResourceBundle.java:960) at
org.hibernate.validator.engine.ResourceBundleMessageInterpolator.loadBundle(ResourceBundleMessageInterpolator.java:202)
at
org.hibernate.validator.engine.ResourceBundleMessageInterpolator.getFileBasedResourceBundle(ResourceBundleMessageInterpolator.java:182)
at
org.hibernate.validator.engine.ResourceBundleMessageInterpolator.(ResourceBundleMessageInterpolator.java:81)
at
org.hibernate.validator.engine.ResourceBundleMessageInterpolator.(ResourceBundleMessageInterpolator.java:73)
at
org.hibernate.validator.engine.ConfigurationImpl.(ConfigurationImpl.java:57)
at
org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
at
javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
... 53 more
My IDE is MyEclipse 9, and I am using JavaEE 6 libraries.
I think my applicationContext.xml is fine, 'cuz it works fine when I run this project in tomcat, no exceptions.
Here is my SessionFactory bean in applicationContext.xml:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="c3p0DataSource" />
<property name="packagesToScan">
<list>
<value>com.myproject.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
How can I do tests using JUnit 4 correctly?
I expect you've got the path to the application-context.xml wrong, as Spring sees it. I'd first try dropping off WebRoot/.
I'd attach the Spring sources to my project and hook-up a debugger, breaking on line:
org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
In there, you'll see where it's loading the application context and you can use an interactive expression executer to try multiple different strings to figure out what it can and can't see.
I'd also try this:
#ContextConfiguration(locations = { "classpath*:applicationContext*.xml" })
That work's in my project where the files are in WEB-INF/classes in the deployment.
Do you really use your production applicaton context for tests?
I would change the approach to use a different application context for tests (e.g. for defining test data sources and stuff) and place it along with your other test resources. Then a simple lookup as the following one will do.
#ContextConfiguration("/path/to/my/test-context.xml")
In your example, you have to make sure the path is correct! Your file URL should be translated to a folder relative to your project's root folder. Does the application context lie there?
#ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})
I think you do not locate your Spring context configuration file from file:// . re-locate it.
I also had this problem, in my case the problem was with the application context xml configuration file being loaded. It was not a properly defined application context. To be precise, "xmlns:context="http://www.springframework.org/schema/context" namespace was missing.
I too have same problem, When I updated both src/test/resources/ApplicationResource.properties and src/main/resources/ApplicationResource.proerties.
And I updated, POM.xml with context and test dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
</dependency>
The src/test/resources/ApplicationContext.xml loaded successfully.
My problem got solved.

Categories

Resources