mehere
mehere

Reputation: 1556

JSF Hibernate Connection Establishment

I am trying to establish connection to my db using hibernate. This project includes JSF 2.1, Hibernate 3, Primefaces. I got this project to run. But when I enter the values into usercreate.xhtml and press add the error mentioned in stacktrace appears.

Jar Files Included are

usercreate.xhtml

<h:head>

</h:head>
<h:body>
    <h:form>
        <table>
            <tr>
                <td><h:outputLabel for="name" value="Name"/></td>
                <td><h:inputText id="name" value="#{userManagedBean.name}">

                </h:inputText></td>

            </tr>
            <tr>
                <td><h:outputLabel for="pwd" value="Password"/></td>
                <td><h:inputSecret id="pwd" value="#{userManagedBean.password}">

                </h:inputSecret></td>

            </tr>
            <tr>
                <td><h:outputLabel for="address" value="Address"/></td>
                <td><h:inputText id="address" value="#{userManagedBean.address}">

                </h:inputText></td>

            </tr>
            <tr>
                <p:commandButton id="add" value="Add" action="#{userManagedBean.addUser}"> </p:commandButton>
                <p:commandButton id="reset" value="Reset" action="#{userManagedBean.reset}"/>
            </tr>
        </table>

    </h:form>

</h:body>

Managed Bean

 public class UserManagedBean implements Serializable {
        private static final long serialVersionUID = 1L;
        private String name;
        private String password;
        private String address;
        private static final String SUCCESS = "success";
        private static final String ERROR   = "error";
//getter and setter of name, password, address included.

    public void addUser()
    {
        User u = new User();
        u.setName(name);
        u.setPwd(password);
        u.setAddress(address);

        String result = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
               tx = session.beginTransaction();
               session.save(u);
               tx.commit();
               result = SUCCESS;
          } catch (Exception e) {
               if (tx != null) {
                tx.rollback();
                result = ERROR;
                e.printStackTrace();
               }
              } finally {
               session.close();
              }

    }

}

User Model

@Entity
@Table(name = "tbl_employee")
public class User {
    private String name;
    private String pwd;
    private String address;

    @Column(name="name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Column(name="pwd")
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Column(name="address")
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

Util

public class HibernateUtil {

    private static SessionFactory sessionFactory = null;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        }
        return sessionFactory;
    }

    public static void setSessionFactory(SessionFactory sessionFactory) {
        HibernateUtil.sessionFactory = sessionFactory;
    }
}

Hibernate Configuration File

<hibernate-configuration>
    <session-factory>
        <property name='hibernate.connection.driver_class'>com.mysql.jdbc.Driver</property>
        <property name='hibernate.connection.url'>jdbc:mysql://localhost:3306/db_employee_spring</property>
        <property name='hibernate.connection.username'>root</property>
        <property name='hibernate.connection.password'>root</property>
        <property name='hibernate.connection.pool_size'>10</property>
        <property name='show_sql'>true</property>
        <property name='dialect'>org.hibernate.dialect.MySQLDialect</property>
        <!-- Mapping files -->
        <!-- <mapping resource='hbm/user.hbm.xml' />-->
    </session-factory>
</hibernate-configuration>

Stacktrace

WARNING: #{userManagedBean.addUser}: java.lang.NoSuchFieldError: INSTANCE
javax.faces.FacesException: #{userManagedBean.addUser}: java.lang.NoSuchFieldError: INSTANCE
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.faces.el.EvaluationException: java.lang.NoSuchFieldError: INSTANCE
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 26 more
Caused by: java.lang.NoSuchFieldError: INSTANCE
    at org.hibernate.type.BasicTypeRegistry.<init>(BasicTypeRegistry.java:94)
    at org.hibernate.type.TypeResolver.<init>(TypeResolver.java:59)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:250)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:302)
    at com.sphc.util.HibernateUtil.getSessionFactory(HibernateUtil.java:12)
    at com.sphc.managedbeans.UserManagedBean.addUser(UserManagedBean.java:49)
    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.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 27 more

I think there is mistake (which i am not able to figure) in addUser method as I am able to access the the addUser method (by sysout) on clicking add button from the xhtml..

Upvotes: 0

Views: 543

Answers (2)

Matt
Matt

Reputation: 3353

Putting it in an answer as there was too much text to comment on Vinayak's answer.

That sort of class cast exception is very common when you have the same class in different libraries / different versions. Good chance you are having a classloader conflict of some sort that would be resolved by removing any libraries you don't need / using correct versions.

Looking back through some of my old hibernate projects I can see I have used hibernate-commons-annotations but not hibernate-annotations (not sure whether this is correct but worked for me).

It's also worth seeing exactly which version of hibernate you are using; in my case, I used (again, not saying it's perfect but worked for me):

hibernate-core-3.6.5.Final.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
mysql-connector-java-5.1.6.jar

If you can I strongly suggest using Maven to manage your dependencies as all the correct dependencies will be pulled in just by adding a couple of libraries.

One other thing you can try is opening the hibernate jar files with something like Winzip or 7zip, and clicking through the folder structure inside to see which ones contain the classes mentioned in the class cast exception - this at least will give you an idea about what the offending libraries are. The other thing to remember is that if you are deploying this onto a webserver anything more complex than an embedded jetty server, there is a good chance that the webserver (eg Tomcat?) can also have its own libraries, especially if someone put them there for a different project (a big no-no, but I do it a lot when prototyping).

Hope that helps!!

Upvotes: 1

Vinayak Pingale
Vinayak Pingale

Reputation: 1315

I have faced similar issue while dealing with JSF.

what you can try out is :-

  1. I had to delete hibernate-annotations.jar, because I had it already in hibernate3.jar.
  2. in the reset command as suggested by L-Ray. @ is not at all acceptable use #.

Upvotes: 1

Related Questions