-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: JNDI with hibernate Tomcat and Eclipse
PostPosted: Fri Oct 03, 2008 12:43 pm 
Newbie

Joined: Fri Oct 03, 2008 3:42 am
Posts: 3
Hi all.
I have a problem.
I use:
Hibernate 3.2.2Beta1
Eclipse SDK 3.3.2
Java jre1.6.0_04
Mysql 5
Tomcat 5.5

I have created a dynamic web application with Eclipse.
I have followed the instructions of the guide http://docs.jboss.org/tools/2.1.0.Beta1 ... index.html # plugins.
I have created the file:
- Hibernate.cfg.xml,

Code:
<?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.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/orange</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
              <mapping resource="data/HsHrEmployee.hbm.xml" />
    </session-factory>
</hibernate-configuration>


- Hibernate.reveng.xml

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >
<hibernate-reverse-engineering>
   <table-filter match-schema="orange" match-name=".*" />
   <table-filter match-name="hs_hr_employee" match-catalog="orange"></table-filter>
</hibernate-reverse-engineering>


Hibernate tools have generated the Domain, DAO and Mapping.

Employee.java:
Code:
public class  HsHrEmployee implements java.io.Serializable {

   private int empNumber;
   private String employeeId;
   private String empLastname;
   private String empFirstname;
.
.
.
public int getEmpNumber() {
      return this.empNumber;
   }

   public void setEmpNumber(int empNumber) {
      this.empNumber = empNumber;
   }

   public String getEmployeeId() {
      return this.employeeId;
   }

   public void setEmployeeId(String employeeId) {
      this.employeeId = employeeId;
   }

   public String getEmpLastname() {
      return this.empLastname;
   }

   public void setEmpLastname(String empLastname) {
      this.empLastname = empLastname;
   }

   public String getEmpFirstname() {
      return this.empFirstname;
   }

   public void setEmpFirstname(String empFirstname) {
      this.empFirstname = empFirstname;
   }
}


EmployeeHome.java:
Code:
public class HsHrEmployeeHome {

   private static final Log log = LogFactory.getLog(HsHrEmployeeHome.class);

   private final SessionFactory sessionFactory = getSessionFactory();

   protected SessionFactory getSessionFactory() {
      try {
         return (SessionFactory) new InitialContext().lookup("SampleSessionFactory");
      } catch (Exception e) {
         log.error("Could not locate SessionFactory in JNDI", e);
         throw new IllegalStateException(
               "Could not locate SessionFactory in JNDI");
      }
   }

   public void persist(HsHrEmployee transientInstance) {
      log.debug("persisting HsHrEmployee instance");
      try {
         sessionFactory.getCurrentSession().persist(transientInstance);
         log.debug("persist successful");
      } catch (RuntimeException re) {
         log.error("persist failed", re);
         throw re;
      }
   }

   public void attachDirty(HsHrEmployee instance) {
      log.debug("attaching dirty HsHrEmployee instance");
      try {
         sessionFactory.getCurrentSession().saveOrUpdate(instance);
         log.debug("attach successful");
      } catch (RuntimeException re) {
         log.error("attach failed", re);
         throw re;
      }
   }

   public void attachClean(HsHrEmployee instance) {
      log.debug("attaching clean HsHrEmployee instance");
      try {
         sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
         log.debug("attach successful");
      } catch (RuntimeException re) {
         log.error("attach failed", re);
         throw re;
      }
   }

   public void delete(HsHrEmployee persistentInstance) {
      log.debug("deleting HsHrEmployee instance");
      try {
         sessionFactory.getCurrentSession().delete(persistentInstance);
         log.debug("delete successful");
      } catch (RuntimeException re) {
         log.error("delete failed", re);
         throw re;
      }
   }

   public HsHrEmployee merge(HsHrEmployee detachedInstance) {
      log.debug("merging HsHrEmployee instance");
      try {
         HsHrEmployee result = (HsHrEmployee) sessionFactory
               .getCurrentSession().merge(detachedInstance);
         log.debug("merge successful");
         return result;
      } catch (RuntimeException re) {
         log.error("merge failed", re);
         throw re;
      }
   }

   public HsHrEmployee findById(int id) {
      log.debug("getting HsHrEmployee instance with id: " + id);
      try {
         HsHrEmployee instance = (HsHrEmployee) sessionFactory
               .getCurrentSession().get("data.HsHrEmployee", id);
         if (instance == null) {
            log.debug("get successful, no instance found");
         } else {
            log.debug("get successful, instance found");
         }
         return instance;
      } catch (RuntimeException re) {
         log.error("get failed", re);
         throw re;
      }
   }

   public List<HsHrEmployee> findByExample(HsHrEmployee instance) {
      log.debug("finding HsHrEmployee instance by example");
      try {
         List<HsHrEmployee> results = (List<HsHrEmployee>) sessionFactory
               .getCurrentSession().createCriteria("data.HsHrEmployee")
               .add(create(instance)).list();
         log.debug("find by example successful, result size: "
               + results.size());
         return results;
      } catch (RuntimeException re) {
         log.error("find by example failed", re);
         throw re;
      }
   }
}


HsHrEmployee.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 3-ott-2008 12.20.40 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="data.HsHrEmployee" table="hs_hr_employee" catalog="orange">
        <id name="empNumber" type="int">
            <column name="emp_number" />
            <generator class="assigned" />
        </id>
        <property name="employeeId" type="string">
            <column name="employee_id" length="50" unique="true" />
        </property>
        <property name="empLastname" type="string">
            <column name="emp_lastname" length="100" not-null="true" />
        </property>
        <property name="empFirstname" type="string">
            <column name="emp_firstname" length="100" not-null="true" />
        </property>
        ..............................
    </class>
</hibernate-mapping>


if I use HQL Editor and run the query:
Code:

form HsHrEmployee

the query is successful.
If I use the following code:
Code:
HsHrEmployee employe = new HsHrEmployee();
HsHrEmployeeHome home = new HsHrEmployeeHome();
employe.setEmpNumber(2);
employe.setEmpFirstname("JavaCognome");
employe.setEmpLastname("JavaNome");
home.persist(employe);      


the system generates the following error:

Code:

[ERROR] Could not locate SessionFactory in JNDI
javax.naming.NameNotFoundException: Name SessionFactory is not bound in this Context
   at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
   at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
   at org.apache.naming.SelectorContext.lookup(SelectorContext.java:137)
   at javax.naming.InitialContext.lookup(Unknown Source)
   at data.HsHrEmployeeHome.getSessionFactory(HsHrEmployeeHome.java:26)
   at data.HsHrEmployeeHome.<init>(HsHrEmployeeHome.java:22)
   at test.Prova.saluto(Prova.java:13)
   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 org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:165)
   at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
   at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
   at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:100)
   at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:176)
   at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275)
   at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:133)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
   at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
   at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
   at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
   at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
   at java.lang.Thread.run(Unknown Source)




I have configured JNDI as follows
I have included in the file web.xml the following code:
Code:

<resource-env-ref>
      <description>Sample Hibernate SessionFactory</description>
      <resource-env-ref-name>hibernate/SampleSessionFactory</resource-env-ref-name>
      <resource-env-ref-type>org.hibernate.SessionFactory</resource-env-ref-type>
   </resource-env-ref>


I have included in the file server.xml the following code:
Code:

<Context >
<Resource name="hibernate/SampleSessionFactory"
             auth="Container"
             type="org.hibernate.SessionFactory"
             factory="data.HibernateSessionFactoryTomcatFactory"
             configuration="hibernate.cfg.xml"/>
     </Context>



I have created the class for the factory
Code:
public class HibernateSessionFactoryTomcatFactory implements ObjectFactory{
   public Object getObjectInstance(Object obj, Name name, Context cntx, Hashtable env)
                 throws NamingException{

      SessionFactory sessionFactory = null;
      RefAddr addr = null;
     
      try{
         Enumeration addrs = ((Reference)(obj)).getAll();
           
         while(addrs.hasMoreElements()){
            addr = (RefAddr) addrs.nextElement();
            if("configuration".equals((String)(addr.getType()))){
               sessionFactory = (new Configuration()).configure((String)addr.getContent()).buildSessionFactory();
            }
         }
      }catch(Exception ex){
         throw new javax.naming.NamingException(ex.getMessage());
      }

      return sessionFactory;
   }
}


I have changed the look up in the HsHrEmployeeHome
Code:
protected SessionFactory getSessionFactory() {
      try {
         return (SessionFactory) new InitialContext().lookup("java:comp/env/hibernate/SampleSessionFactory");
      } catch (Exception e) {
         log.error("Could not locate SessionFactory in JNDI", e);
         throw new IllegalStateException(
               "Could not locate SessionFactory in JNDI");
      }
   }




But the system generates the following problem
Code:
INFO: Not binding factory to JNDI, no JNDI name configured
[ERROR] persist failed
org.hibernate.HibernateException: persist is not valid without active transaction
   at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338)
   at $Proxy4.persist(Unknown Source)
   at data.HsHrEmployeeHome.persist(HsHrEmployeeHome.java:37)
   at test.Prova.saluto(Prova.java:24)
   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 org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:165)
   at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
   at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
   at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:100)
   at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:176)
   at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275)
   at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:133)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
   at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
   at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
   at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
   at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
   at java.lang.Thread.run(Unknown Source)


Help me please.
Where is the fault ?


Top
 Profile  
 
 Post subject:
PostPosted: Mon Oct 06, 2008 10:01 am 
Newbie

Joined: Fri Oct 03, 2008 3:42 am
Posts: 3
I found solution:

Code:
public void persist(HsHrEmployee transientInstance) {
      log.debug("persisting HsHrEmployee instance");
      Transaction  tx = sessionFactory.getCurrentSession().beginTransaction();
      try {
         sessionFactory.getCurrentSession().persist(transientInstance);
         tx.commit();
         log.debug("persist successful");
      } catch (RuntimeException re) {
         tx.rollback();
         log.error("persist failed", re);
         throw re;
      }
   }


Top
 Profile  
 
 Post subject:
PostPosted: Mon Oct 13, 2008 6:52 pm 
Newbie

Joined: Mon Oct 13, 2008 6:46 pm
Posts: 3
andrexx wrote:
I found solution:

Code:
public void persist(HsHrEmployee transientInstance) {
      log.debug("persisting HsHrEmployee instance");
      Transaction  tx = sessionFactory.getCurrentSession().beginTransaction();
      try {
         sessionFactory.getCurrentSession().persist(transientInstance);
         tx.commit();
         log.debug("persist successful");
      } catch (RuntimeException re) {
         tx.rollback();
         log.error("persist failed", re);
         throw re;
      }
   }


i have the same problem, tomcat Could not locate SessionFactory in JNDI ..
and i use eclipse europa, tomcat , hibernate 3.2 and tomcat 5.5
could you tell me what you do in addition to the code u posted
thanks a lot for your help


Top
 Profile  
 
 Post subject: Re: JNDI with hibernate Tomcat and Eclipse
PostPosted: Fri May 18, 2012 12:15 am 
Newbie

Joined: Thu May 17, 2012 9:29 pm
Posts: 1
Did you find any better way of doing with out manually modifying Home Class. Because i dont want to commit a transaction if im updating multiple table. could u please help me


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.