Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration Exception - noclassdeffounderror

I am learning Hibernate and tried a simple program. I used Hibernate 5.3 version and added all the Hibernate required .jar files to the build path. I can find the Configuration class in the ref libraries folder, still getting the exception. Is there anything wrong with the hibernate.cfg.xml? Is there any specific location it has to be saved? Please help me. Thanks in advance.
I am attaching my project layout and source code.
my HibernateUtil.java code
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
System.out.println("hii");
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;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
[Project layout]project layoutHibernate confg xml file

Related

Javax.naming.NameNotFoundException: when trying to look up the jndi name in JavaEE and Wildfly

I am doing some unit testing using javaee and wildly so I am in the client project trying to lookup the jndi name remotely in order to test a service located of course in the ejb, all is fine and the handshake is done correctly but while testing I am getting an exeception which is:
test.ServiceLocatorException: javax.naming.NameNotFoundException:
/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
Here is a snippet showing the appname, modulename and this is how I am trying to lookup the jndi:
java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
java:module/ClientSessionBean!utilities.CllientSessionBeanRemote
java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
java:module/ClientSessionBean!utilities.CllientSessionBeanLoacal
Client Code:
public class JunitTester {
public static final String jndi = "java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote" ;
private static CllientSessionBeanRemote getProxy() {
return (CllientSessionBeanRemote) ServiceLocator.getInstance().getProxy(jndi);
}
#org.junit.Test
public void Test() throws NamingException {
System.out.println(JunitTester.getProxy().Verify_No_Existence("Multiskan"));}
Any advice could help, thanks.
with your client code I was able to run on glassfish successfully....
Below is the code having said that
if you can test again please give me the exact exception.
Ensure Client.jar is in your classpath in my case its gf-client.jar
server up and running and you than connect the client
Junit
package com.au.clients;
import com.au.ejbs.GreetingI;
import javax.naming.NamingException;
public class JunitTester {
public static final String jndi = "java:global/ejb3_2_ear_exploded/ejb/Greeting";
private static GreetingI getProxy() throws NamingException {
return (GreetingI) ServiceLocator.getInstance().getProxy(jndi);
}
#org.junit.Test
public void Test() throws NamingException {
System.out.println(getProxy().Verify_No_Existence("Multiskan"));
}
}
Service locator
import com.au.ejbs.GreetingI;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
public static ServiceLocator getInstance() {
ServiceLocator serviceLocator = null;
if(serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public static GreetingI getProxy(String jndi) throws NamingException {
InitialContext context =new InitialContext();
GreetingI greeting = context.doLookup(jndi);
return greeting;
}
}
output
true
Process finished with exit code 0

EJB not initializing in Wildfly 9.0.0 using #EJB

I'm trying to migrate from EJB2.x to EJB3.x and i'm using Wildfly 9.0.0.
The old EJB2.x is working in JBoss 4.2.2 and this is how it looks like:
public interface WUFFacadeRemote extends EJBObject {
public ClientData getItems(ClientData data);
public ClientData save(ClientData data);
}
public interface WUFFacadeHome extends EJBHome {
public WUFFacadeRemote create();
}
public class WUFFacade {
public ClientData getItems(ClientData data) {
//code here
}
public ClientData save(ClientData data) {
//code here
}
}
public class WUFAction extends HttpServlet implements IAction {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
...
Object objRef = ic.lookup("java:comp/env/wUF");
com.wuf.WUFFacadeHome home = (com.wuf.WUFFacadeHome) PortableRemoteObject.narrow(objRef, com.wuf.WUFFacadeHome.class);
engine = home.create();
//engine gets the reference, and I can use it normally.
...
}
}
I also have the ejb-jar.xml and it's working. Now, the solution I was thinking to EJB3.x and Wildfly 9.0.0 is as below:
#WebServlet(urlPatterns = "windows/wUF.do", loadOnStartup = 1)
public class WUFAction extends HttpServlet implements IAction {
#EJB
private WUFFacadeRemote engine;
public void doPost(HttpServletRequest request, HttpServletResponse response) {
//Here I should be able to use my engine.
//Wildfly starts and I call the page, engine is not null at this moment,
//but after I call the page again, it becomes null and remains null.
}
}
#Stateless
#Remote(WUFFacadeRemote.class)
public class WUFFacade extends RootFacade implements WUFFacadeRemote, Serializable {
public WUFFacade() { }
#EJB
FUFHome home;
public ClientData getItems(ClientData data) {
//code here
}
public ClientData save(ClientData data) {
//code here
}
private Col load(ClientData data,InitialContext ic) {
//here i'm calling home.
// but home is always null. It was supposed to have the #EJB reference initialized.
//But instead I get a null pointer...
home.findByFilter(loader);
}
}
#Remote(FUFHome.class)
public interface FUFHome {
FUF create(FUFValue fUFValue);
FUF findByPrimaryKey(FUFPK pk);
Collection findByFilter(FacadeLoader loader);
}
public interface WUFFacadeRemote{
public ClientData getItems(ClientData data);
public ClientData save(ClientData data);
}
I don't have ejb-jar.xml anymore, the deploy is sucessfully done and Wildfly starts with no errors. Then the first time I call the page in question, it seems that #EJB is working (Debug is "Proxy for remote EJB StatelessEJBLocator for "bus-facade/WUFFacade", view is interface com.wuf.WUFFacadeRemote, affinity is None"), the value is not null, but for all subsequent calls, my variable is null and I got a NullPointerException.
I really don't know what i'm doing wrong (maybe i'm completely lost), but to me, #EJB should be working correctly like that. What am I missing? Thanks.
As i'm using EJB3.x i'm just using annotations now, (this seems to be ok).
JNDIs:
JNDI bindings for session bean named FUF in deployment
java:global/fumo/bus-entities-fumo/FUF!apyon.components.fumo.fuf.FUF
java:app/bus-entities-fumo/FUF!apyon.components.fumo.fuf.FUF
java:module/FUF!apyon.components.fumo.fuf.FUF
java:global/fumo/bus-entities-fumo/FUF
java:app/bus-entities-fumo/FUF
java:module/FUF
JNDI bindings for session bean named WUFFacade
java:global/fumo/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:app/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:module/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:jboss/exported/fumo/bus-facade-fumo/WUFFacade!apyon.fumo.wuf.WUFFacadeRemote
java:global/fumo/bus-facade-fumo/WUFFacade
java:app/bus-facade-fumo/WUFFacade
java:module/WUFFacade
I think I found a possible solution to the problem. I'll still try to find another one, but this is good so far.
After changing to a .war and keeping my other projects in .ears it's working. Maybe the problem was because I have a RootController servlet im my main.ear, which is the starting point of the aplication. The context starts there and then it redirects to fumo.ear (now fumo.war).
For some reason, I always was getting a null in my EJB after entering a page. It was always hapening when I first entered a JSP and tried to call the page again. My solution to this is:
#WebServlet(urlPatterns = "windows/wUF.do", loadOnStartup = 1)
public class WUFAction extends HttpServlet {
private WUFFacadeRemote engine;
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
doPost(req, resp);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
if(engine == null) {
InitialContext ic;
try {
ic = new InitialContext();
engine = (WUFFacadeRemote) ic.lookup("java:global/fumo/WUFFacade!fumo.wuf.WUFFacadeRemote");
} catch (NamingException e) {
e.printStackTrace();
}
}
//here I always have the context now.
}
}
And as a .war my structure now looks like this:
So other annotations like #Inject and #EJB are now working. Always when i'm being redirect from a JSP calling a Servlet or some action, I first check if the context is not null, otherwise I lookup it. My #Stateless are working and the #PersistenceContext and #Remote are working too.
#Stateless
public class WUFFacade implements WUFFacadeRemote {
#Inject
private FUFRules rules;
#EJB
private FUFHome home;
private Col load(ClientData data, InitialContext ic) throws InterfaceException {
try {
// home here is nor null anymore.
Collection res = (Collection) home.findByFilter(loader);
...
} catch (InterfaceException e) {
e.printStackTrace();
}
...
return data;
}
}
So I'd like to thank everyone who helped in the thread. It was a good way to understand and see the problem or to find a workaround. As I said, I'll still try the .ear in the future, but as a simplified packaging it definitely works.

Unable to persist object in database using Spring data jpa Repositories and JtaTransactionManager

trying to find what went wrong with my code which worked fine until i moved to JTAtransactionManager it is having issue saving the record in database but fetching the record working fine, below is my sample TransactionConfig class and service class method.
#Configuration
#ComponentScan
#EnableTransactionManagement
public class TransactionConfig {
#Bean(name = "userTransaction")
public UserTransaction userTransaction() throws Throwable {
UserTransactionImp userTransactionImp = new UserTransactionImp();
//userTransactionImp.setTransactionTimeout(10000);
return userTransactionImp;
}
#Bean(name = "atomikosTransactionManager", initMethod = "init", destroyMethod = "close")
public TransactionManager atomikosTransactionManager() throws Throwable {
UserTransactionManager userTransactionManager = new UserTransactionManager();
userTransactionManager.setForceShutdown(false);
return userTransactionManager;
}
#Bean(name = "transactionManager")
#DependsOn({ "userTransaction", "atomikosTransactionManager" })
public PlatformTransactionManager transactionManager() throws Throwable {
UserTransaction userTransaction = userTransaction();
TransactionManager atomikosTransactionManager = atomikosTransactionManager();
return new JtaTransactionManager(userTransaction, atomikosTransactionManager);
}
}
---Employee Service Class Method---
#Transactional
public void appExample() {
try {
Employee emp = new Employee();
emp.setFirstName("Veer");
emp.setLastName("kumar");
empRepo.save(emp);
} catch (Exception e) {
log.error(e);
}
}
I think issue is with empRepo.save() method call. This call is not committing any changes to database as you are using #Transactional for transaction management.
Please try with empRepo.saveAndFlush() which will immediately flush the data into database. You can refer answer Difference between save and saveAndFlush in Spring data jpa

Hibernate error while compiling

I am trying to incorporate Hibernate v4 in my Dynamic Web project in eclipse. I am using Maven for dependencies. I wrote all the code and created entity classes and mapping xml files but on building project I get this error
The project was not built since its build path is incomplete. Cannot find the class file for javax.naming.Referenceable.
Fix the build path then try building this project MyProject
I wrote HibernateUtil class as this:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
if (sessionFactory == null) {
Configuration configuration = new Configuration()
.configure(HibernateUtil.class
.getResource("/hibernate.cfg.xml"));
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration
.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder
.build();
sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
EDIT: I get this error on getSessionFactory method call in shutdown method.
Anyone knows what can be problem?
The problem lies in you trying to use the Referenceable interface class somewhere and that class is not available on the build path. Like it says, you must fix the build path. Do this by providing the package that has javax.naming.Referenceable.
What I find strange is why rewrite the HibernateUtil class? This is probably not something you want to do here. And I see no explanation as to why you would write your own.
I would recommend forget the HibernateUtil class and start using the Hibernate framework in its entirety.

hibernate.cfg.xml not found on the JBoss server on OpenShift

Friends'm trying to connect my application in openshift through hibernate orm.
But the deployment is failing. You can check the error message in the server log:
2013/01/03 14:02:59,296 ERROR [com.wavetech_st.util.HibernateUtil] (MSC service thread 1-4) Falha na criação do objeto SessionFactory: org.hibernate.HibernateException: hibernate.cfg.xml not found
2013/01/03 14:02:59,298 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/testehome]] (MSC service thread 1-4) Exception starting filter conexaoFilter: java.lang.ExceptionInInitializerError
at com.wavetech_st.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:26) [classes:]
at com.wavetech_st.util.HibernateUtil.(HibernateUtil.java:12) [classes:]
at com.wavetech_st.web.filter.ConexaoHibernateFilter.init(ConexaoHibernateFilter.java:31) [classes:]
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:447) [jbossweb-7.0.10.Final.jar:]
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3269) [jbossweb-7.0.10.Final.jar:]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3865) [jbossweb-7.0.10.Final.jar:]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.0.Final.jar:7.1.0.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.7.0_09-icedtea]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.7.0_09-icedtea]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_09-icedtea]
Caused by: org.hibernate.HibernateException: resources/hibernate.cfg.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1943) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at org.hibernate.cfg.Configuration.configure(Configuration.java:1924) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at com.wavetech_st.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) [classes:]
... 11 more
I am creating this application in Eclipse. I have tested it on the local server JBoss 7.1 and it works. However when I try remote gives the error. I set the file hibernate.cfg the datasource before you deploy to OpenShift:
<property name="connection.datasource">java:jboss/datasources/MysqlDS</property>
This is my directory structure:
This is my WebFilter:
package com.wavetech_st.web.filter;
import java.io.IOException;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import com.wavetech_st.util.HibernateUtil;
public class ConexaoHibernateFilter implements Filter {
private SessionFactory sf;
#Override
public void init(FilterConfig config) throws ServletException {// executado quando o aplicativo web e colocado no ar
this.sf = HibernateUtil.getSessionFactory();
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
try {
this.sf.getCurrentSession().beginTransaction();
chain.doFilter(servletRequest, servletResponse);
this.sf.getCurrentSession().getTransaction().commit();
this.sf.getCurrentSession().close();
} catch (Throwable ex) {
try {
if(this.sf.getCurrentSession().getTransaction().isActive())
this.sf.getCurrentSession().getTransaction().rollback();
} catch (Throwable t) {
t.printStackTrace();
}
throw new ServletException(ex);
}
}
#Override
public void destroy() {}
}
This is my HibernateUtil:
<pre>
package com.wavetech_st.util;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
static final Logger logger = Logger.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
return cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
logger.error("Falha na criação do objeto SessionFactory: " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Please, help :-/
I solved my problem by following the hint of these guys:
stackoverflow.com/questions/4934330/org-hibernate-hibernateexception-hibernate-cfg-xml-not-found
shaunabram.com/tag/hibernate/
My problem was to put the hibernate.cfg.xml file in the wrong location. How to use Maven I should not put in the root directory but in the src directory root resouces.
Thanks mate, I had the same problem in jBoss-Openshift and Mybatis but with your answer you help me, I attached a picture where I put Mybatis config file who is similar file as hibernate