對象-關係映射(ORM)提供了一個框架,應用程序可以使用一個對象範例,查詢並操作數據庫中的數據。該框架以多種語言實現,封裝了數據操作所需的代碼。這樣,您無需瞭解SQL,即可使用一個對象訪問數據,該對象隱藏了每個數據庫查詢語言的變化。
假設有以下的Employees表:
ID | Name | Address | Department | Salary |
---|---|---|---|---|
1 | John | Milpitas, CA | Engineer | $100,000 |
2 | Tom | Cupertino, CA | Support | $80,000 |
3 | James | Sunnyvale, CA | Pubs | $70,000 |
4 | Mike | San Jose, CA | Marketing | $95,000 |
5 | Maya | Fremont, CA | Sales Rep | $80,000 |
以下示例在Employees表中檢索可獲得的ID、Name和Salary列:
SQL> SELECT ID, NAME, SALARY FROM Employees where ID = 1;
如果用編程的方式,您必須創建以下代碼:
String selectSQL = “SELECT ID, NAME FROM Employees WHERE ID = 1” ;
Statement = dbConnection.createStatement() ;
ResultSet rs = Statement.executeQuery(selectSQL ) ;
while (rs.next())
{
String userid = rs.getString(“ID”) ;
String username = rs.getString(“NAME”) ;
}
但是,ORM的代碼爲:
Employee_list = EmployeeTable.query(ID=1) ;
如您所見,ORM簡化了複雜的代碼。除此之外,ORM還具有以下優點:
- 數據模型在一個地方,節約時間。
- 便於代碼的更新、維護和重新使用。
- 使用您的首選編程語言,靈活性高。
當然,您必須要花點時間學習ORM。Hibernate (Java)、Propel或Doctrine (PHP)、Django或SQLAlchemy (Python)周圍有很多ORM。
本文重點討論Hibernate。Hibernate ORM (Hibernate)是一個Java的對象-關係映射框架,提供面向對象的域模型-傳統關係型數據庫的映射。Hibernate用高層級的對象處理函數替代直接的持久化相關數據庫訪問,解決了對象-關係的抗阻失配問題。Hibernate是自由軟件,符合GNU寬通用公共許可協議2.1。功能包括Java類-數據庫表的映射(和Java數據類型-SQL數據類型的映射)、數據查詢和檢索。Hibernate生成SQL調用,減輕開發人員的手動結果集處理和對象轉換。使用Hibernate的應用程序是非常輕便的,只需很小的性能開銷,即可支持SQL數據庫。
Hibernate位於傳統的Java對象和數據庫服務器之間,根據適當的O/R機制和模式,處理持久化這些對象的所有操作。
Hibernate採用分層架構,分離了底層的API。Hibernate利用數據庫和配置數據,嚮應用程序提供持久化服務(和持久對象)。下圖顯示了Hibernate的高層架構:
接下來,瞭解Trafodion如何支持Hibernate框架。若要支持Hibernate,數據庫的供應商必須創建一個方言,該方言要能夠實現最佳性能、能夠利用豐富的功能。有些功能/函數可能只在Trafodion(或其他數據庫)中可用,不受Hibernate的支持。在這種情況下,Hibernate SQL方言會將您的Hibernate應用程序翻譯成SQL語言,與您的數據庫進行通信。我們創建了一個Trafodion方言,如果遇到Hibernate應用程序,Hibernate將解析此類功能。Trafodion方言的JIRA:https://hibernate.atlassian.n...。
使用Trafodion方言的步驟和示例代碼
1.創建Trafodion數據庫表。
*SET SCHEMA TRAFODION.SEABASE;
DROP TABLE employee;
CREATE TABLE EMPLOYEE (
id INT NOT NULL ,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
CREATE SEQUENCE trafodion.seabase.empseq;*
2.創建POJO類。
Employee.java的內容:
package trafodion.hibernate.common;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
HibernateUtil.java的內容:
package trafodion.hibernate.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
3.創建映射配置文件。
以下文件告訴Hibernate如何映射Java類型-數據庫表:
Employee.hbm.xml文件的內容:
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”
該Java類包含員工的詳細信息:
trafodion.seabase.empseq
Trafodion數據庫的hibernate配置文件內容:
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
false
org.trafodion.jdbc.t4.T4Driver
zz
jdbc:t4jdbc://10.12.10.21:12345/:
zz
org.hibernate.dialect.TrafodionDialect
true
4.創建應用程序類文件(ManageEmployee.java)。
package trafodion.hibernate.common;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("AAA", "Ali", 1000);
Integer empID2 = ME.addEmployee("BBB", "Das", 5000);
Integer empID3 = ME.addEmployee("CCC", "Paul", 10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* List down all the employees */
ME.listEmployees();
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Query qry= session.createQuery("FROM Employee");
List employees= qry.list();
//List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
致謝:感謝ADP首席數據科學家,Haifeng Li爲Trafodion方言作出的貢獻