Hibernate mapping exception even though mappings appear correct

137 views Asked by At

I've this Java application in package com.luv2code.hibernate.demo:

package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.luv2code.hibernate.demo.entity.Employee;

public class CreateEmployeeDemo {

    public static void main(String[] args) {
        
        // create session factory
        SessionFactory factory = new Configuration()
                                        .configure("hibernate.cfg.xml")
                                        .addAnnotatedClass(Employee.class)
                                        .buildSessionFactory();
        
        // create a session
        Session session = factory.getCurrentSession();
        
        try {
            
            // create the employee object
            System.out.println("Creating a new employee object...");
            Employee  tempEmployee = new Employee("John", "Doe", "Doe Corp.");
            
            // start a transaction
            session.beginTransaction();
            
            // save the employee object
            System.out.println("Saving the employee...");
            session.save(tempEmployee);
            
            // commit the transaction
            session.getTransaction().commit();
            
            // find the employee's ID: primary key
            System.out.println("Save employee. Generated ID: " + tempEmployee.getId());
            
            // now get a new session and start transaction
            session = factory.getCurrentSession();
            session.beginTransaction();
            
            // retrieve employee based on the ID: primary key
            System.out.println("\nGettin employee with id: " + tempEmployee.getId());
            
            Employee myEmployee = session.get(Employee.class, tempEmployee.getId());
            
            System.out.println("Get complete: " + myEmployee);
            
            // commit the transaction
            session.getTransaction().commit();
            
            // delete student id=2
            System.out.println("Deleting student id=2");
            session.createQuery("delete from Student where id = '2'").executeUpdate();
            
            
            // commit the transaction
            session.getTransaction().commit();
            
            System.out.println("Done!");
            
        }
        finally {
            factory.close();
        }

    }

}

It uses this Employee class in package com.luv2code.hibernate.demo.entity:

package com.luv2code.hibernate.demo.entity;

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

public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    
    @Column(name="first_name")
    private String firstName;
    
    @Column(name="last_name")
    private String lastName;
    
    @Column(name="company")
    private String company;

    public Employee() {
        
    }

    public Employee(String firstName, String lastName, String company) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.company = company;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", company=" + company + "]";
    }
}

When I run the program I get this error:

Saving the employee...
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC]
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections close
ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.luv2code.hibernate.demo.entity.Employee
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1606)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:114)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:634)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:627)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:622)
    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:498)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:351)
    at com.sun.proxy.$Proxy25.save(Unknown Source)
    at com.luv2code.hibernate.demo.CreateEmployeeDemo.main(CreateEmployeeDemo.java:33)

I can't see what could be wrong here. It seems to be a mapping exception but I think my mappings should be correct. Can anybody spot the issue?

1

There are 1 answers

0
Eklavya On BEST ANSWER

Use @Entity and @Table for map database table name with Employee class

@Entity
@Table(name = "employee")
public class Employee { ... }