[學習筆記] 在Eclipse中使用Hibernate,並建立第一個工程,資料庫為Oracle XE
前文參考:Oracle 11g xe 在windows安裝
在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安裝請看如下連結:
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;
如果再次執行會增加新的記錄。
至此,本文完成