проблемы java hibernate

122
03 августа 2019, 12:10

первый раз делаю hibernate возникла ошибка. В java новичок подскажите куда копать.

янв 10, 2019 8:09:32 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.0.Final}
янв 10, 2019 8:09:32 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Failed to create sessionFactory object.java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
Exception in thread "main" java.lang.ExceptionInInitializerError
    at employee.ManageEmployee.main(ManageEmployee.java:31)
Caused by: java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
    at org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:345)
    at org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:337)
    at org.hibernate.cfg.Environment.<clinit>(Environment.java:230)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:78)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:67)
    at org.hibernate.cfg.Configuration.reset(Configuration.java:158)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:124)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)
    at employee.ManageEmployee.main(ManageEmployee.java:24)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.NamingStrategy$SuffixingRandom$BaseNameResolver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 9 more
    C:\Users\alsem\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
    СБОРКА ЗАВЕРШЕНА СО СБОЕМ (общее время: 2 секунды)

и собственно файлы

package employee;
import java.util.List; 
import java.util.Date;
import java.util.Iterator; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try {
         factory = new Configuration().
                   configure().
                   //addPackage("com.xyz") //add package if used.
                   addAnnotatedClass(Employee.class).
                   buildSessionFactory();
      } catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();


      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);


      ME.listEmployees();

      ME.updateEmployee(empID1, 5000);

      ME.deleteEmployee(empID2);
      ME.listEmployees();
   }
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try {
         tx = session.beginTransaction();
         Employee employee = new Employee();
         employee.setFirstName(fname);
         employee.setLastName(lname);
         employee.setSalary(salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      } catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      } finally {
         session.close(); 
      }
      return employeeID;
   }


   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try {
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      } catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      } finally {
         session.close(); 
      }
   }


   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(); 
      }
   }
   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(); 
      }
   }
} 

package employee;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;
   @Column(name = "first_name")
   private String firstName;
   @Column(name = "last_name")
   private String lastName;
   @Column(name = "salary")
   private int salary; 
    public static void main(String[] args) {
        // TODO code application logic here
    }
    public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

`

и собственно hibernate.cfg.xml

`

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost/music_shop</property>   
    <property name="connection.username">postgres</property>
    <property name="connection.password">postgres</property>
    <property name="connection.pool_size">1</property>
    <property name= "cache.provider_class">
        org.hibernate.cache.NoCacheProvider
    </property>
      <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
      <property name="show_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
      <property name="current_session_context_class">thread</property>
   </session-factory>
</hibernate-configuration>

`

Answer 1

Ошибка, похоже, возникает в этой строке:

addAnnotatedClass(Employee.class).

Ваш класс Employee описан аннотациями? Приложите его.

READ ALSO
Не могу распарсить JSON

Не могу распарсить JSON

Хочу распарсить Json от Yandex Geocoder для получения адреса по координатам, но не могуЧто я делаю не так?

123
Сортировка списков

Сортировка списков

Необходимо из списка чисел составить новый список, состоящий из чисел, которые останутся на своем месте список отсортировать по возрастанию,...

112
Примитив или что-то другое?

Примитив или что-то другое?

В языке программирования Java всё является объектом, исключение составляют примитивыКонтейнером для примитивов являются переменные примитивных...

135