English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
我们可以简单地将hibernate应用程序与spring应用程序集成。
在hibernate框架中,我们提供了所有功能数据库信息hibernate.cfg.xml文件。
但是,如果我们要将hibernate应用程序与spring集成在一起,则无需创建hibernate.cfg.xml文件。我们可以在applicationContext.xml文件中提供所有信息。
Spring框架提供了 HibernateTemplate 类,因此您无需执行太多步骤,例如创建Configuration,BuildSessionFactory,Session,开始和提交事务等。
因此 它节省了大量代码.
不使用spring的理解问题:
下面的休眠代码让我们理解它:
//创建配置 Configuration cfg=new Configuration(); cfg.configure("hibernate.cfg.xml"); // Creare l'oggetto session factory SessionFactory factory = cfg.buildSessionFactory(); // Creare l'oggetto sessione Session session = factory.openSession(); // Creare l'oggetto transazione Transaction t = session.beginTransaction(); Employee e1 = new Employee(111, "arun", 40000); session.persist(e1); // Persisting the object t.commit(); // Commit della transazione session.close();
Come puoi vedere nel codice Hibernate unico, devi seguire molti passaggi.
Soluzione con la classe HibernateTemplate del framework Spring:
Ora, non è necessario eseguire molti passaggi. Puoi semplicemente scrivere così:
Employee e1 = new Employee(111, "arun", 40000); hibernateTemplate.save(e1);
Ecco una lista dei metodi comuni della classe HibernateTemplate.
Metodo | Descrizione |
void persist(Object entity) | Sostentare l'oggetto fornito. |
Serializable save(Object entity) | Retenere l'oggetto fornito e restituire l'ID. |
void saveOrUpdate(Object entity) | Persistere o aggiornare l'oggetto fornito. Se trova l'id, aggiornerà la registrazione, altrimenti salvare la registrazione. |
void update(Object entity) | Aggiornare l'oggetto fornito. |
void delete(Object entity) | Eliminare l'oggetto fornito in base all'id. |
Object get(Class entityClass, Serializable id) | Restituire l'oggetto persistente in base all'id fornito. |
Object load(Class entityClass, Serializable id) | Restituire l'oggetto persistente in base all'id fornito. |
List loadAll(Class entityClass) | Restituire tutti gli oggetti persistenti. |
Vediamo quali sono i semplici passaggi per l'integrazione di sleep e spring:
Creare una tabella nel databaseQuesto è opzionale. Crea il file applicationContext.xml. Contiene informazioni su DataSource, SessionFactory, ecc. Crea il file Employee.java. È la classe persistente Crea il file employee.hbm.xml. È il file di mappatura. Crea il file EmployeeDao.java. È una classe DAO utilizzata HibernateTemplate. Crea il file InsertTest.java. Chiamerà i metodi della classe EmployeeDao.
In questo esempio, integreremo l'applicazione Hibernate con Spring. Vediamo l'esempio di integrazione di Hibernate e Spring Struttura del catalogo.
1、Crea la tabella nel database
In questo esempio, utilizziamo Oracle come database, ma puoi utilizzare qualsiasi database. Creiamo la tabella nel database Oracle
CREATE TABLE "EMP558" ( "ID" NUMBER(10,0) NOT null ENABLE, "NAME" VARCHAR2(255 CHAR), "SALARY" float(126), PRIMARY KEY ("ID") ENABLE ) /
2、Employee.java
Questa è una semplice classe POJO. In questo esempio, viene utilizzata come classe persistente di Hibernate.
package com.w3codebox; public class Employee { private int id; private String name; private float salary; //getters and setters }
3、employee.hbm.xml
Questo file di mappatura contiene tutte le informazioni delle classi persistenti.
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.w3codebox.Employee" table="emp558"> <id name="id"> <generator class="assigned"></generator> </id> <property name="name"></property> <property name="salary"></property> </class> </hibernate-mapping>
4、EmployeeDao.java
这是使用 HibernateTemplate Java类,用于持久保存Employee类对象的类方法。
package com.w3codebox; import org.springframework.orm.hibernate3.HibernateTemplate; import java.util.*; public class EmployeeDao { HibernateTemplate template; public void setTemplate(HibernateTemplate template) { this.template = template; } //保存职员的方法 public void saveEmployee(Employee e){ template.save(e); } //更新员工的方法 public void updateEmployee(Employee e){ template.update(e); } //删除职员的方法 public void deleteEmployee(Employee e){ template.delete(e); } //方法返回一个具有给定 id 的雇员 public Employee getById(int id){ Employee e=(Employee)template.get(Employee.class,id); return e; } //method to return all employees public List<Employee> getEmployees(){ List<Employee> list=new ArrayList<Employee>(); list=template.loadAll(Employee.class); return list; } }
5、applicationContext.xml
In questo file, stiamo BasicDataSource The object provides all the information of the database. This object is used LocalSessionFactoryBean The object of the class, which contains some other information, such as mappingResources and hibernateProperties. LocalSessionFactoryBean The object of the class is used in the HibernateTemplate class. Let's take a look at the code of the applicationContext.xml file.
File: applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property> <property name="username" value="system"></property> <property name="password" value="oracle"></property> </bean> <bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>employee.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="mysessionFactory"></property> </bean> <bean id="d" class="com.w3codebox.EmployeeDao"> <property name="template" ref="template"></property> </bean> </beans>
6, InsertTest.java
Questa classe utilizza l'oggetto della classe EmployeeDao e chiama il metodo saveEmployee passando l'oggetto della classe Employee.
package com.w3codebox; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class InsertTest { public static void main(String[] args) { Resource r = new ClassPathResource("applicationContext.xml"); BeanFactory factory = new XmlBeanFactory(r); EmployeeDao dao = (EmployeeDao)factory.getBean("d"); Employee e = new Employee(); e.setId(114); e.setName("varun"); e.setSalary(50000); dao.saveEmployee(e); } }
Ora, se vedete la tabella nel database Oracle, il record è stato inserito con successo.
È possibile abilitare le proprietà hibernate nell'archivio applicationContext.xml, ad esempio tramite hbm2ddl.auto per la creazione automatica delle tabelle. Vediamo il codice:
<property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props>
Se si scrive questo codice, non è necessario creare la tabella, poiché verrà creata automaticamente.