[學習筆記] 在Eclipse中使用Hibernate,並創建第一個Demo工程,數據庫為Oracle XE

前文參考:

在Eclipse中使用Hibernate

安裝 Hibernate Tools 插件

https://tools.jboss.org/downloads/

Add the following URL to your Eclipse 4.13 (2019-09) installation, via:

Help > Install New Software… > Work with:

http://download.jboss.org/jbosstools/photon/stable/updates/

Then select the individual features that you want to install:

點擊Next

點擊Next
同意相關協議,點擊Finish .

則會開始下載安裝。

視網絡速度,可能需要幾分鐘到十幾分鐘的時間才能完成安裝。

最後會提示重啟Eclipse才能生效。

在Eclipse中新建Hibernate應用

File->New -> Java Project

點擊Finish

項目結構圖

在Eclipse中新建用戶庫

此時下面显示了已經建立的用戶庫列表

我們要添加Hibernate的依賴庫,因此點擊用戶庫

Hibernate_4.3.5_final

選擇jar文件

項目結構圖

繼續配置Hibernate

最後自動形成 如下的文件內容:[本例使用oracle數據庫]

Oracle 11g xe 在windows安裝請看如下鏈接:

hibernate.cfg.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.connection.username">test</property>
        <property name="hibernate.default_schema">test</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
    </session-factory>
</hibernate-configuration>

再增加幾個屬性

配置文件更新后的內容如下: 注意要去掉name屬性 更改 為

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory >
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.password">123456</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:xe:orcl</property>
  <property name="hibernate.connection.username">test</property>
  <property name="hibernate.default_schema">test</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.show_sql">true</property>
  <!-- 第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以後加載hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器后,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來后才會。 -->
  <property name="hibernate.hbm2ddl.auto">update</property> 
  <property name="hibernate.format_sql">true</property>
  <property name="hibernate.default_entity_mode">pojo</property>
 </session-factory>
</hibernate-configuration>

繼續完善工程Hibernate_demo_001

新建一個包:mytest001.demo

在包mytest001.demo之下新建一個PO類: Emp

package mytest001.demo;

public class Emp {
    // 員工的標識屬性
    private Integer id;
    // 姓名
    private String name;
    // 年齡
    private Integer age;
    // 工資 (分)
    private Integer salary;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSalary() {
        return salary;
    }

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

    @Override
    public String toString() {
        return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
    }
}

此刻此PO Emp.java 尚不具備持久化能力。下面為其添加註解。

@Entity 註解聲明該類是一個Hibernate持久化類
@Table 指定該類映射的表,對應的數據庫表名是T_EMP
@Id 指定該類的標識屬性,映射到數據庫的主鍵列
@GeneratedValue(strategy=GenerationType.SEQUENCE) 指定了主鍵生成策略,由於本文使用Oracle Database, 因此指定了使用 SEQUENCE

在hibernate.cfg.xml中增加持久化映射類名

增加一個新類:EmpManager,用於管理員工。

package mytest001.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.Service;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class EmpManager {

    public static void main(String[] args)  throws Exception  {
         
    //實例化配置
    Configuration configuration  = new Configuration()
            //不帶參數則默認加載hibernate.cfg.xml
            .configure();
    
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    SessionFactory sFactory = configuration.buildSessionFactory(serviceRegistry);
    
    //創建session 
    Session session = sFactory.openSession();
    
    //開始事務
    Transaction tx = session.beginTransaction();
    //創建員工對象
    Emp emp = new Emp();
    // 設置員工信息
    emp.setAge(28);
    emp.setName("scott");
    emp.setSalary(10000);
    session.save(emp);
    // 提交事務
    tx.commit();
    session.close();
    sFactory.close();
            
    
    }

}

最後配置文件的內容:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory >
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.password">123456</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
  <property name="hibernate.connection.username">test</property>
  <property name="hibernate.default_schema">test</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.show_sql">true</property>
  <!-- 第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以後加載hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器后,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來后才會。 -->
  <property name="hibernate.hbm2ddl.auto">update</property> 
  <property name="hibernate.format_sql">true</property>
  <property name="hibernate.default_entity_mode">pojo</property>
  <mapping class="mytest001.demo.Emp"/>
 </session-factory>
</hibernate-configuration>

Emp.java

package mytest001.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="T_EMP")
public class Emp {
    // 員工的標識屬性
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private Integer id;
    // 姓名
    private String name;
    // 年齡
    private Integer age;
    // 工資 (分)
    private Integer salary;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSalary() {
        return salary;
    }

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

    @Override
    public String toString() {
        return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
    }
}

最後的工程結構如下:

運行EmpManger

十一月 23, 2019 8:50:47 上午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
十一月 23, 2019 8:50:47 上午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:xe]
十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=test, password=****}
十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
十一月 23, 2019 8:50:48 上午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
十一月 23, 2019 8:50:48 上午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
十一月 23, 2019 8:50:48 上午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: T_EMP
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: T_EMP
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: T_EMP
十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: 
    select
        test.hibernate_sequence.nextval 
    from
        dual
Hibernate: 
    insert 
    into
        test.T_EMP
        (age, name, salary, id) 
    values
        (?, ?, ?, ?)
十一月 23, 2019 8:50:48 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]

到數據庫中查詢表:(這個表會被自動創建)
select * from t_emp;

如果再次運行會增加新的記錄。

至此,本文完成。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理【其他文章推薦】

※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

您可能也會喜歡…