0

I'm trying to develop my first simple webapp using java and hibernate, and it doesn't work.

This is the error:

 org.hibernate.MappingException: Unknown entity: com.csm.app1st.model.User
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1606)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:675)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:667)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:662)
    at com.csm.app1st.controller.AddUser.doPost(AddUser.java:40)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

this is my code

adduser:

package com.csm.app1st.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.csm.app1st.model.User;

/**
 * Servlet implementation class AddUser
 */
@WebServlet(description = "Create new user Servlet", urlPatterns = { "/CreateUser.do" })
public class AddUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {

        Configuration config = new Configuration().configure();
        ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
        SessionFactory factory = config.buildSessionFactory(servReg);

        Session session = factory.openSession();
        session.beginTransaction();
        User u = new User(request.getParameter("firstname"), request.getParameter("lastname"), request.getParameter("country"));
        session.save(u);
        session.getTransaction().commit();
        session.close();

        RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
        view.forward(request, response);
    }

}

user

    package com.csm.app1st.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")

public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id", nullable=false, unique=true)
private int id;

@Column(name="firstname", length=40, nullable=false)
private String firstname;

@Column(name="lastname", length=40, nullable=false)
private String lastname;

@Column(name="country", length=40, nullable=true)
private String country;

public User(String firstname, String lastname, String country) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.country = country;
}

get & set...

}

config file hibernate

 <hibernate-configuration>
    <session-factory>

        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/firstapp</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="show_sql">false</property>

        <mapping class="com.csm.app1st.model.User" />

    </session-factory>
</hibernate-configuration>

I don't know why it doesn't work. can you help me please?

pom.xml

<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>first_project</groupId>
  <artifactId>first_project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
  • Is your hibernate configuration file named `hibernate.cfg.xml`? Where is it placed in your project? – pleft Oct 19 '16 at 12:52
  • This will probably not fix your current problem, but one error i found: Hibernate entities allways require a default constructor with no arguments. From what i see your User class is missing this default constructor. – OH GOD SPIDERS Oct 19 '16 at 12:55
  • yes the name of configuration file is hibernate.cfg.xml, is a problem? the file position is: Java Resources/src –  Oct 19 '16 at 13:25
  • Wait a bit , you have a web Servlet and in each post request you want to re-open the hibernate Context ?? Please tell me that this is just for testing purposes ........ As mentioned by @elefasGR , either you are mixing the hibernate dependencies , or you are missing some of them. It would be create if you were posting your pom.xml or even your `classpath/lib` directory – AntJavaDev Oct 19 '16 at 13:43
  • This is my first webapp, i'm not an expert. I added the pom.xml –  Oct 19 '16 at 13:49
  • Can't see any `` on your `pom.xml`. Is it complete? – pleft Oct 19 '16 at 13:49
  • ......wow , i cannot imagine from where you are importing the `import org.hibernate.*` dependencies , so maybe you are an expert. ill try to replicate it locally gimme some time – AntJavaDev Oct 19 '16 at 13:50
  • Hmm, probably your project is messed up. If you use maven and `pom.xml` all your project dependencies (jars) like hibernate, must be declared in `pom.xml`. I suggest to follow a tutorial for hibernate with maven there are plenty examples in the web. – pleft Oct 19 '16 at 13:57
  • probably i made a mistake, i converted my project to maven because before there wasn't pom.xml file –  Oct 19 '16 at 14:01
  • ok after adding some missing dependencies and properly configuring your hibernate.cfg.xml it plays well. The first obvious issue is what @elefasGR mentioned and the second one is that on your hibernate configuration you dont create / update the scema tables from classes..... thus user table does not exist – AntJavaDev Oct 19 '16 at 14:27
  • can you write the code please? –  Oct 19 '16 at 14:45
  • ok because i dont know exactly your issue , first try adding this line to your hibernate.cfg.xml : `create`. more info [here](http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do). If this doesnt work i ll post a working solution – AntJavaDev Oct 19 '16 at 15:56

2 Answers2

1

I tried replacing the following code in adduser.java file

Configuration config = new Configuration().configure(); 
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); 
SessionFactory factory = config.buildSessionFactory(servReg);

with

SessionFactory factory = new Configuration().configure()
                .buildSessionFactory();

Rest all same.It's working for me.

Imran Ali
  • 2,223
  • 2
  • 28
  • 41
Remya
  • 35
  • 1
  • 5
0

Since you are using annotations you should change this line:

Configuration config = new Configuration().configure();

to

Configuration config = new AnnotationConfiguration().configure();

A very basic example almost identical to yours can be found at: http://www.concretepage.com/hibernate/example_annotationconfiguration_hibernate

pleft
  • 7,567
  • 2
  • 21
  • 45
  • i did it, but it's doesn't work, this is the error: Multiple markers at this line - The method configure() is undefined for the type AnnotationConfiguration –  Oct 19 '16 at 13:28
  • Strange, which version of hibernate are you using? do you have a `pom.xml` file to post also in your question? – pleft Oct 19 '16 at 13:32
  • I'm using hibernate 5.2.3, I added pom.xml –  Oct 19 '16 at 13:50