使用 Netbeans 休眠获取数据

Fetching data using hibernate with Netbeans

我正在尝试使用 Hibernate 从 MySQL 数据库中获取数据。为了实现这样的目标,我创建了:

  1. 休眠配置文件:

    <?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. 实用程序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. 主要class:

public class EmployeesApp 扩展 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();
    }
}

编辑: 4.员工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(){
    }

}

当谈到 运行 代码时,我没有从数据库中获取行,只是一些通用的 SELECT 子句(最后一行)。 我究竟做错了什么?

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**

您必须覆盖 Employee class 中的 public String toString() 方法。

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

System.out.println(emp); 方法只是打印以控制 toString() 方法 return 值

Employee@53b7f657

内部会调用,

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

对象 class 中该方法的实现是

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

因此,如果您的 class 上没有 'custom' public String toString(),这就是您将看到的内容,因为 每个 class 都是隐式地是 Object.

的子class

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.

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