例子

    创建应用程序的第一步就是建立 Java 的 POJO 类或者其它类,这取决于即将要存放在数据库中的应用程序。我们可以考虑一下让我们的 Employee 类使用 getXXXsetXXX 方法从而使它们变成符合 JavaBeans 的类。

    POJO (Plain Old Java Object) 是 Java 的一个对象,这种对象不会扩展或者执行一些特殊的类并且它的接口都是分别在 EJB 框架的要求下的。所有正常的 Java 对象都是 POJO。

    当你设计一个存放在 Hibernate 中的类时,最重要的是提供支持 JavaBeans 的代码和在 Employee 类中像 id 属性一样可以当做索引的属性。

    1. id INT NOT NULL auto_increment,
    2. first_name VARCHAR(20) default NULL,
    3. last_name VARCHAR(20) default NULL,
    4. salary INT default NULL,
    5. PRIMARY KEY (id)
    6. );

    这一步是创建一个映射文件从而指导 Hibernate 如何对数据库的表映射定义的类。

    你需要将映射文档以<classname>.hbm.xml的格式保存在一个文件中。我们将映射文档保存在 Employee.hbm.xml文件中。下面让我们看看映射文档相关的一些小细节:

    • 映射文档是一个 XML 格式的文档,它拥有<hibernate-mapping>作为根元素,这个元素包含了所有的 <class>元素。
    • <class> 元素被用来定义从 Java 类到数据库表的特定的映射。Java 类的名称是特定的,它使用的是类元素的 name 属性,数据库表的名称也是特定的,它使用的是 table 属性。
    • <meta> 元素是一个可选元素,它可以用来创建类的描述。
    • <id> 元素向数据库的主要关键字表映射类中的特定的 ID 属性。id 元素的 name 属性涉及到了类中的属性同时 column 属性涉及到了数据库表中的列。type 属性掌握了 hibernate 的映射类型,这种映射类型将会从 Java 转到 SQL 数据类型。
    • id 元素中的 <generator>元素是用来自动产生主要关键字的值的。将 generator 元素的 class 属性设置成 native 从而使 Hibernate 运用 identity, sequence 或者 hilo 算法依靠基础数据库的性能来创建主要关键字。
    • <property> 元素是用来映射一个 Java 类的属性到数据库的表中的列中。这个元素的 name 属性涉及到类中的属性,column 属性涉及到数据表中的列。type 属性控制 Hibernate 的映射类型,这种映射类型将会从 Java 转到 SQL 数据类型。

    映射文档中还有许多其它的属性和元素,在探讨其它的 Hibernate 相关的话题时我将会详细进行讲解。

    1. import java.util.List;
    2. import java.util.Date;
    3. import java.util.Iterator;
    4. import org.hibernate.HibernateException;
    5. import org.hibernate.Session;
    6. import org.hibernate.Transaction;
    7. import org.hibernate.SessionFactory;
    8. import org.hibernate.cfg.Configuration;
    9. public class ManageEmployee {
    10. private static SessionFactory factory;
    11. public static void main(String[] args) {
    12. try{
    13. factory = new Configuration().configure().buildSessionFactory();
    14. }catch (Throwable ex) {
    15. System.err.println("Failed to create sessionFactory object." + ex);
    16. throw new ExceptionInInitializerError(ex);
    17. }
    18. ManageEmployee ME = new ManageEmployee();
    19. /* Add few employee records in database */
    20. Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
    21. Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
    22. Integer empID3 = ME.addEmployee("John", "Paul", 10000);
    23. /* List down all the employees */
    24. ME.listEmployees();
    25. /* Update employee's records */
    26. /* Delete an employee from the database */
    27. ME.deleteEmployee(empID2);
    28. /* List down new list of the employees */
    29. ME.listEmployees();
    30. }
    31. /* Method to CREATE an employee in the database */
    32. public Integer addEmployee(String fname, String lname, int salary){
    33. Session session = factory.openSession();
    34. Transaction tx = null;
    35. Integer employeeID = null;
    36. try{
    37. tx = session.beginTransaction();
    38. Employee employee = new Employee(fname, lname, salary);
    39. employeeID = (Integer) session.save(employee);
    40. tx.commit();
    41. }catch (HibernateException e) {
    42. if (tx!=null) tx.rollback();
    43. e.printStackTrace();
    44. }finally {
    45. session.close();
    46. }
    47. return employeeID;
    48. }
    49. /* Method to READ all the employees */
    50. public void listEmployees( ){
    51. Session session = factory.openSession();
    52. Transaction tx = null;
    53. try{
    54. tx = session.beginTransaction();
    55. List employees = session.createQuery("FROM Employee").list();
    56. for (Iterator iterator =
    57. employees.iterator(); iterator.hasNext();){
    58. Employee employee = (Employee) iterator.next();
    59. System.out.print("First Name: " + employee.getFirstName());
    60. System.out.print(" Last Name: " + employee.getLastName());
    61. System.out.println(" Salary: " + employee.getSalary());
    62. }
    63. tx.commit();
    64. }catch (HibernateException e) {
    65. if (tx!=null) tx.rollback();
    66. e.printStackTrace();
    67. }finally {
    68. session.close();
    69. }
    70. /* Method to UPDATE salary for an employee */
    71. Session session = factory.openSession();
    72. Transaction tx = null;
    73. try{
    74. tx = session.beginTransaction();
    75. Employee employee =
    76. (Employee)session.get(Employee.class, EmployeeID);
    77. employee.setSalary( salary );
    78. session.update(employee);
    79. tx.commit();
    80. }catch (HibernateException e) {
    81. if (tx!=null) tx.rollback();
    82. e.printStackTrace();
    83. }finally {
    84. session.close();
    85. }
    86. }
    87. /* Method to DELETE an employee from the records */
    88. public void deleteEmployee(Integer EmployeeID){
    89. Session session = factory.openSession();
    90. Transaction tx = null;
    91. try{
    92. tx = session.beginTransaction();
    93. Employee employee =
    94. (Employee)session.get(Employee.class, EmployeeID);
    95. session.delete(employee);
    96. tx.commit();
    97. }catch (HibernateException e) {
    98. if (tx!=null) tx.rollback();
    99. e.printStackTrace();
    100. }finally {
    101. session.close();
    102. }
    103. }
    104. }

    下面是编译和运行上述提到的应用程序的步骤。在编译和执行应用程序之前确保你已经设置好了 PATH 和 CLASSPATH。

    • 创建设置章节中所讲的 hibernate.cfg.xml 配置文件。
    • 创建上文所述的 Employee.hbm.xml 映射文件。
    • 创建上文所述的 Employee.java 源文件并且进行编译。
    • 创建上文所述的 ManageEmployee.java 源文件并且进行编译。
    • 执行二进制的 ManageEmployee 来运行程序。

    你将会得到如下结果,记录将会在 EMPLOYEE 表中建立。

    如果你检查你的 EMPLOYEE 表,它将会有如下记录:

    1. mysql> select * from EMPLOYEE;
    2. +----+------------+-----------+--------+
    3. | id | first_name | last_name | salary |
    4. +----+------------+-----------+--------+
    5. | 29 | Zara | Ali | 5000 |
    6. | 31 | John | Paul | 10000 |
    7. +----+------------+-----------+--------+
    8. 2 rows in set (0.00 sec