首页 > 解决方案 > Fetching data using hibernate with Netbeans

问题描述

I'm trying to use Hibernate in order to get data from MySQL database. In order to achieve such a goal, I have created:

  1. Hibernate configuration file:

    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/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/employeesDbAF
            </property>
    
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password"></property>
            <property name="hibernate.connection.pool_size">50</property>
            <property name="show_sql">true</property>
            <property name="dialect">
                org.hibernate.dialect.MySQLDialect
            </property>
            <property name="hibernate.hbm2ddl.auto">validate</property>
    
    
        <mapping class="employeesapp.Employee"></mapping>    
        </session-factory>
    </hibernate-configuration>
    
  2. Utility class

    public class HibernateUtil {
    
        private static SessionFactory sessionFactory;
        private static ServiceRegistry serviceRegistry;
    
        public static SessionFactory createSessionFactory() {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).build();
            //sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            sessionFactory = configuration.buildSessionFactory();
            return sessionFactory;
        }
    
        public static void close() {
            StandardServiceRegistryBuilder.destroy(serviceRegistry);
    
        }
    
    }
    
  3. Main class:

public class EmployeesApp extends javax.swing.JFrame {

public static void main(String[] args) {        

    Session session = HibernateUtil.createSessionFactory().openSession();
    Transaction tx = null;

    try {
        tx = session.beginTransaction();
        Employee emp = (Employee)session.get(Employee.class, 2);
        System.out.println(emp);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        System.out.println(e);
    } finally {
        HibernateUtil.close();
    }
}

EDIT: 4. Employee class:

    @Entity
    @Table(name="employee")    
    public class Employee { 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="employee_ID")
    private int employee_ID;
    @Column(name="name")
    private String name;
    @Column(name="age")
    private int age;
    @Column(name="address")
    private String address;
    @Column(name="salary")
    private int salary;

    public int getEmployee_ID() {return employee_ID;}

    public void setEmployee_ID(int employee_ID) {this.employee_ID = employee_ID; }    

    public String getName() {return name;    }

    public void setName(String name) {this.name = name;    }

    public int getAge() {return age;}

    public void setAge(int age) {this.age = age;    }

    public String getAddress() {return address;    }

    public void setAddress(String address) {this.address = address;    }

    public int getSalary() {return salary;    }

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

    public Employee(int employee_ID, String name, int age, String address, int salary) {
        //this.employee_ID = employee_ID;
        this.name = name;
        this.age = age;
        this.address = address;
        this.salary = salary;
    }

    public Employee(){
    }

}

When it comes to run code, I'm not getting row from the database, just some generic SELECT clause (last row). What am I doing wrong?

run:
Jun 05, 2019 10:53:26 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/employeesDbAF]
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 50 (min=1)
Jun 05, 2019 10:53:27 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jun 05, 2019 10:53:27 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jun 05, 2019 10:53:27 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: employeesDbAF.employee
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [address, employee_id, name, salary, age]
**Hibernate: select employee0_.employee_ID as employee1_0_0_, employee0_.address as address2_0_0_, employee0_.age as age3_0_0_, employee0_.name as name4_0_0_, employee0_.salary as salary5_0_0_ from employee employee0_ where employee0_.employee_ID=?
employeesapp.Employee@53b7f657**

标签: javahibernatepersistence

解决方案


You have to override public String toString() method in Employee class.

@Override
public String toString() {
    return "Employee{" +
            "employee_ID=" + employee_ID +
            ", name='" + name + '\'' +
            ", age=" + age +
            ", address='" + address + '\'' +
            ", salary=" + salary +
            '}';
}

System.out.println(emp); method just print to console the toString() method return value

Employee@53b7f657

Internally it will call,

// java.io.PrintStream    
public void println(Object x) {
            String s = String.valueOf(x);
            synchronized (this) {
                print(s);
                newLine();
            }
        }

// java.lang.String
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

And the implementation of that method in Object class is

// java.lang.Object    
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, if you do not have a 'custom' public String toString() on your class, that's what you will see because of every class is implicitly a subclass of Object.

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Source https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html


推荐阅读