JavaEE09-Hibernate的使用

Hibernate的使用

Hibernate配置文件

可有手工编写Hibernate配置文件, 或者
NetBeans项目中的源包上点击右键, 新建->其它->Hibernate->Hibernate配置向导, 可以自动生成的Hibernate配置文件hibernate.cfg.xml内容如下:

<?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.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
  </session-factory>
</hibernate-configuration>

Hibernate逆向工程配置文件

可有手工编写Hibernate逆向工程配置文件, 或者
NetBeans项目中的源包上点击右键, 新建->其它->Hibernate->Hibernate逆向工程向导, 可以自动生成的Hibernate逆向工程配置文件hibernate.reveng.xml内容如下:

<?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-schema="APP"/>
  <table-filter match-name="DISCOUNT_CODE"/>
  <table-filter match-name="CUSTOMER"/>
  <table-filter match-name="MICRO_MARKET"/>
</hibernate-reverse-engineering>

执行逆向工程

如果手工根据表写对应的类, 工作量可能很大. 逆向工程自动生成很快得到的正确的代码.
NetBeans项目中的源包上点击右键, 新建->其它->Hibernate->通过数据库生成Hibernate映射文件和POJO
自动生成的对象关系映射文件Customer.hbm.xml文件内容如下:

<?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 2018-5-14 15:19:56 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="model.Customer" table="CUSTOMER" schema="APP" optimistic-lock="version">
        <id name="customerId" type="int">
            <column name="CUSTOMER_ID" />
            <generator class="assigned" />
        </id>
        <property name="discountCode" type="char">
            <column name="DISCOUNT_CODE" length="1" not-null="true" />
        </property>
        <property name="zip" type="string">
            <column name="ZIP" length="10" not-null="true" />
        </property>
        <property name="name" type="string">
            <column name="NAME" length="30" />
        </property>
        <property name="addressline1" type="string">
            <column name="ADDRESSLINE1" length="30" />
        </property>
        <property name="addressline2" type="string">
            <column name="ADDRESSLINE2" length="30" />
        </property>
        <property name="city" type="string">
            <column name="CITY" length="25" />
        </property>
        <property name="state" type="string">
            <column name="STATE" length="2" />
        </property>
        <property name="phone" type="string">
            <column name="PHONE" length="12" />
        </property>
        <property name="fax" type="string">
            <column name="FAX" length="12" />
        </property>
        <property name="email" type="string">
            <column name="EMAIL" length="40" />
        </property>
        <property name="creditLimit" type="java.lang.Integer">
            <column name="CREDIT_LIMIT" />
        </property>
    </class>
</hibernate-mapping>

自动生成对应的Java类Customer.java内容如下:

package model;
/**
 * Customer generated by hbm2java
 */
public class Customer implements java.io.Serializable {

    private int customerId;
    private char discountCode;
    private String zip;
    private String name;
    private String addressline1;
    private String addressline2;
    private String city;
    private String state;
    private String phone;
    private String fax;
    private String email;
    private Integer creditLimit;

    public Customer() {
    }

    public Customer(int customerId, char discountCode, String zip) {
        this.customerId = customerId;
        this.discountCode = discountCode;
        this.zip = zip;
    }

    public Customer(int customerId, char discountCode, String zip, String name, String addressline1, String addressline2, String city, String state, String phone, String fax, String email, Integer creditLimit) {
        this.customerId = customerId;
        this.discountCode = discountCode;
        this.zip = zip;
        this.name = name;
        this.addressline1 = addressline1;
        this.addressline2 = addressline2;
        this.city = city;
        this.state = state;
        this.phone = phone;
        this.fax = fax;
        this.email = email;
        this.creditLimit = creditLimit;
    }

    public int getCustomerId() {
        return this.customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public char getDiscountCode() {
        return this.discountCode;
    }

    public void setDiscountCode(char discountCode) {
        this.discountCode = discountCode;
    }

    public String getZip() {
        return this.zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getName() {
        return this.name;
    }

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

    public String getAddressline1() {
        return this.addressline1;
    }

    public void setAddressline1(String addressline1) {
        this.addressline1 = addressline1;
    }

    public String getAddressline2() {
        return this.addressline2;
    }

    public void setAddressline2(String addressline2) {
        this.addressline2 = addressline2;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPhone() {
        return this.phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getFax() {
        return this.fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getCreditLimit() {
        return this.creditLimit;
    }

    public void setCreditLimit(Integer creditLimit) {
        this.creditLimit = creditLimit;
    }
}

在执行逆向工程时会在Hibernate配置文件中自动填入各个对象关系映射文件名称. 修改后的hibernate.cfg.xml文件内容如下:

<?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.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <mapping resource="model/MicroMarket.hbm.xml"/>
    <mapping resource="model/DiscountCode.hbm.xml"/>
    <mapping resource="model/Customer.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Hibernate工具类

NetBeans项目中的源包上点击右键, 新建->其它->Hibernate->HibernateUtil.java
自动生成的Hibernate工具类NewHibernateUtil.java

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 */
public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

编写程序

下面的程序需要手工编写.
Hibernate的启动需要耗时数秒. 启动后的Hibernate执行速度很快. 这里执行了1000次查询.
查询Customer类对应的数据库表, 并显示每个对象(表的每行数据)的name字段的内容. 程序如下:

import java.util.List;
import model.Customer;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Main {

    public static void main(String[] args) {
        final SessionFactory sessionFactory = NewHibernateUtil.getSessionFactory();
        for (int i = 0; i < 1000; i++) {
            action(sessionFactory);
        }
        sessionFactory.close();
    }

    private static void action(final SessionFactory sessionFactory) throws HibernateException {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from Customer");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getName());
        }
        transaction.commit();
        session.close();
    }
}

项目结构

忽略javaapplication1包的内容, 真正需要人工编写的内容只有Main.java文件.
项目结构

猜你喜欢

转载自blog.csdn.net/dlutcat/article/details/80310959