Error inserting data with Hibernate

0

I'm trying to insert data in two tables with a one-to-many mapped with Hibernate in Netbeans, but when I run the application I get the following error:

  

run:   Mar 11, 2017 12:28:20 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager   INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}   Mar 11, 2017 12:28:20 AM org.hibernate.Version logVersion   INFO: HHH000412: Hibernate Core {4.3.1.Final}   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Environment   INFO: HHH000206: hibernate.properties not found   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Environment buildBytecodeProvider   INFO: HHH000021: Bytecode provider name: javassist   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Configuration configure   INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Configuration getConfigurationInputStream   INFO: HHH000040: Configuration resource: /hibernate.cfg.xml   Mar 11, 2017 12:28:20 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity   WARN: HHH000223: Recognized obsolete hibernate namespace link . Use namespace link instead. Refer to Hibernate 3.6 Migration Guide!   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Configuration addResource   INFO: HHH000221: Reading mappings from resource: Entity / Certificate.hbm.xml   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Configuration addResource   INFO: HHH000221: Reading mappings from resource: Entity / Employee.hbm.xml   Mar 11, 2017 12:28:20 AM org.hibernate.cfg.Configuration doConfigure   INFO: HHH000041: Configured SessionFactory: null   Mar 11, 2017 12:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure   WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)   Mar 11, 2017 12:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator   INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc: mysql: // localhost: 3306 / java_util_set? ZeroDateTimeBehavior = convertToNull]   Mar 11, 2017 12:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator   INFO: HHH000046: Connection properties: {user = root, password = ****}   Mar 11, 2017 12:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator   INFO: HHH000006: Autocommit mode: false   Mar 11, 2017 12:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure   INFO: HHH000115: Hibernate connection pool size: 20 (min = 1)   Mar 11, 2017 12:28:20 AM org.hibernate.dialect.Dialect   INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect   Failed to create sessionFactory object.org.hibernate.MappingException: Association references unmapped class: Certificate   Exception in thread "main" java.lang.ExceptionInInitializerError       at java_util_set.Java_util_Set.main (Java_util_Set.java:36)   Caused by: org.hibernate.MappingException: Association references unmapped class: Certificate       at org.hibernate.cfg.HbmBinder.bindCollectionSecondPass (HbmBinder.java:2557)       at org.hibernate.cfg.HbmBinder $ CollectionSecondPass.secondPass (HbmBinder.java:2808)       at org.hibernate.cfg.CollectionSecondPass.doSecondPass (CollectionSecondPass.java:70)       at org.hibernate.cfg.Configuration.originalSecondPassCompile (Configuration.java:1695)       at org.hibernate.cfg.Configuration.secondPassCompile (Configuration.java:1424)       at org.hibernate.cfg.Configuration.buildSessionFactory (Configuration.java:1844)       at org.hibernate.cfg.Configuration.buildSessionFactory (Configuration.java:1928)       at java_util_set.Java_util_Set.main (Java_util_Set.java:33)

Could you tell me how to solve it or tell me where I can get good examples to work all kinds of relationships in Hibernate with Netbeans. These are the codes I have:

Database:

CREATE DATABASE IF NOT EXISTS 'java_util_set' /*!40100 DEFAULT CHARACTER SET latin1 */;
USE 'java_util_set';
CREATE TABLE IF NOT EXISTS 'certificate' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'certificate_name' varchar(30) DEFAULT NULL,
'employee_id' int(11) DEFAULT NULL,
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS 'employee' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'first_name' varchar(20) DEFAULT NULL,
'last_name' varchar(20) DEFAULT NULL,
'salary' int(11) DEFAULT NULL,
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This is the Employee class:

package Entity;
// Generated 10/03/2017 11:27:32 PM by Hibernate Tools 4.3.1

import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Employee generated by hbm2java
 */
@Entity
@Table(name="employee"
    ,catalog="java_util_set"
)
public class Employee {

     private Integer id;
     private String firstName;
     private String lastName;
     private Integer salary;
     private Set certificates;

    public Employee() {
    }

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

     @Id @GeneratedValue(strategy=IDENTITY)

    @Column(name="id", unique=true, nullable=false)
    public Integer getId() {
        return this.id;
    }

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

    @Column(name="first_name", length=20)
    public String getFirstName() {
        return this.firstName;
    }

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

    @Column(name="last_name", length=20)
    public String getLastName() {
        return this.lastName;
    }

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

    @Column(name="salary")
    public Integer getSalary() {
        return this.salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    public Set getCertificates() {
      return this.certificates;
   }

   public void setCertificates( Set certificates ) {
      this.certificates = certificates;
   }
}

This is the Certificate class:

package Entity;
// Generated 10/03/2017 11:27:32 PM by Hibernate Tools 4.3.1

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

/**
 * Certificate generated by hbm2java
 */
@Entity
@Table(name = "certificate", catalog = "java_util_set"
)
public class Certificate  {

    private Integer id;
    private String certificateName;
    private Integer employeeId;

    public Certificate() {
    }

    public Certificate(String certificateName) {
        this.certificateName = certificateName;
        //this.employeeId = employeeId;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

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

    @Column(name = "certificate_name", length = 30)
    public String getCertificateName() {
        return this.certificateName;
    }

    public void setCertificateName(String certificateName) {
        this.certificateName = certificateName;
    }

   /* @Column(name = "employee_id")
    public Integer getEmployeeId() {
        return this.employeeId;
    }

    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }*/

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!this.getClass().equals(obj.getClass())) {
            return false;
        }

        Certificate obj2 = (Certificate) obj;
        if ((this.id == obj2.getId()) && (this.certificateName.equals(obj2.getCertificateName()))) {
            return true;
        }
        return false;
    }

    public int hashCode() {
        int tmp = 0;
        tmp = (id + certificateName).hashCode();
        return tmp;
    }
}

Mapping of employee:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 10/03/2017 11:27:33 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="Entity.Employee"  table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="identity"/>
      </id>
      <set name="certificates" cascade="all">
         <key column="employee_id"/>
         <one-to-many class="Certificate"/>
      </set>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

Certificate Mapping:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 10/03/2017 11:27:33 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
      <class name="Entity.Certificate" table="CERTIFICATE">
      <meta attribute="class-description">
         This class contains the certificate records. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="identity"/>
      </id>
      <property name="certificateName" column="certificate_name" type="string"/>
   </class>
</hibernate-mapping>

Configuration and reverse reengineering:

<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java_util_set?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">*******</property>
    <mapping resource="Entity/Certificate.hbm.xml"/>
    <mapping resource="Entity/Employee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Reingenieria:

<?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>
  <schema-selection match-catalog="java_util_set"/>
  <table-filter match-name="employee"/>
  <table-filter match-name="certificate"/>
</hibernate-reverse-engineering>

This is the java_util_set class:

package java_util_set;

import Entity.Certificate;
import Entity.Employee;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author AFAL3D
 */
public class Java_util_Set {

    /**
     * @param args the command line arguments
     */
    private static SessionFactory factory;

    public static void main(String[] args) {
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        Java_util_Set ME = new Java_util_Set();
        /* Let us have a set of certificates for the first employee  */
        HashSet set1 = new HashSet();
        set1.add(new Certificate("MCA"));
        set1.add(new Certificate("MBA"));
        set1.add(new Certificate("PMP"));

        /* Add employee records in the database */
        Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);

        /* Another set of certificates for the second employee  */
        HashSet set2 = new HashSet();
        set2.add(new Certificate("BCA"));
        set2.add(new Certificate("BA"));

        /* Add another employee record in the database */
        Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);

        /* List down all the employees */
        ME.listEmployees();

        /* Update employee's salary records */
        ME.updateEmployee(empID1, 5000);

        /* Delete an employee from the database */
        ME.deleteEmployee(empID2);

        /* List down all the employees */
        ME.listEmployees();

    }

    /* Method to add an employee record in the database */
    public Integer addEmployee(String fname, String lname,
            int salary, Set cert) {
        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            Employee employee = new Employee(fname, lname, salary);
            employee.setCertificates(cert);
            employeeID = (Integer) session.save(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }

    /* Method to list all the employees detail */
    public void listEmployees() {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List employees = session.createQuery("FROM Employee").list();
            for (Iterator iterator1
                    = employees.iterator(); iterator1.hasNext();) {
                Employee employee = (Employee) iterator1.next();
                System.out.print("First Name: " + employee.getFirstName());
                System.out.print("  Last Name: " + employee.getLastName());
                System.out.println("  Salary: " + employee.getSalary());
                Set certificates = employee.getCertificates();
                for (Iterator iterator2
                        = certificates.iterator(); iterator2.hasNext();) {
                    Certificate certName = (Certificate) iterator2.next();
                    System.out.println("Certificate: " + certName.getCertificateName());
                }
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    /* Method to update salary for an employee */
    public void updateEmployee(Integer EmployeeID, int salary) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee
                    = (Employee) session.get(Employee.class, EmployeeID);
            employee.setSalary(salary);
            session.update(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    /* Method to delete an employee from the records */
    public void deleteEmployee(Integer EmployeeID) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee
                    = (Employee) session.get(Employee.class, EmployeeID);
            session.delete(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
    
asked by afal3d 11.03.2017 в 06:54
source

1 answer

1

It's complicated because it seems you're using some pretty old examples.

In any case, if you look at the exception, it says that:

  

Exception in thread "main" java.lang.ExceptionInInitializerError at java_util_set.Java_util_Set.main (Java_util_Set.java:36) Caused by: org.hibernate.MappingException: Association references unmapped class: Certificate at

that is, it says that the class of objects in Set is Certificate , and that Certificate is not one of the classes mapped (by hibernate), that is, it is not a entity .

Looking at that, we look for how you define the association in Employee.hbm.xml and you have:

  <set name="certificates" cascade="all">
     <key column="employee_id"/>
     <one-to-many class="Certificate"/>
  </set>

; specifically:

     <one-to-many class="Certificate"/>

Certificate is not the full name of the class, so Hibernate does not recognize it as a entity ; the full name is Entity.Certificate , so you should change it to:

     <one-to-many class="Entity.Certificate"/>

In another order of things:

1) the name of the packages should start with lowercase letters ( entity.Certificate ). ALWAYS.

2) The absence of generics, annotations and the use of hbm.xml (apart from some WARNING messages in the log) tells me that you are using quite old examples. Very old. Unless you have to work with old code, I recommend you look for more updated tutorials.

    
answered by 11.03.2017 / 14:45
source