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"); //seession factory 객체 생성 SessionFactory factory=cfg.buildSessionFactory(); //session 객체 생성 Session session=factory.openSession(); //거래 객체 생성 Transaction t=session.beginTransaction(); Employee e1=new Employee(111,"arun",40000); session.persist(e1);//object를 저장하는 중 t.commit();//거래 제출 session.close();
하나의 유일한 Hibernate 코드에서 볼 수 있듯이, 많은 단계를 따라야 합니다.
Spring Framework의 HibernateTemplate 클래스의 해결책을 사용하면:
지금부터는 많은 단계를 수행할 필요가 없습니다. 간단하게 이렇게 작성할 수 있습니다:
Employee e1=new Employee(111,"arun",40000); hibernateTemplate.save(e1);
HibernateTemplate 클래스의 일반적인 메서드 목록을 보겠습니다.
메서드 | 설명 |
void persist(Object entity) | 주어진 객체를 坚持 합니다. |
Serializable save(Object entity) | 주어진 객체를 보존하고 ID를 반환합니다. |
void saveOrUpdate(Object entity) | 지속적이거나 특정 객체를 업데이트합니다. id를 찾으면 기록을 업데이트하고, 찾지 못하면 기록을 저장합니다. |
void update(Object entity) | 주어진 객체를 업데이트합니다. |
void delete(Object entity) | id에 따라 주어진 객체를 삭제합니다. |
Object get(Class entityClass, Serializable id) | 주어진 id에 따라 영구 객체를 반환합니다. |
Object load(Class entityClass, Serializable id) | 주어진 id에 따라 영구 객체를 반환합니다. |
List loadAll(Class entityClass) | 모든 영구 객체를 반환합니다. |
hibernate와 spring 통합의 간단한 단계는 무엇인가요?:
데이터베이스에서 테이블을 생성。이는 선택 사항입니다。 applicationContext.xml 파일을 생성。DataSource, SessionFactory 등의 정보가 포함되어 있습니다。 Employee.java 파일을 생성。이는 영구성 클래스입니다. employee.hbm.xml 파일을 생성。이는 맵핑 파일입니다. EmployeeDao.java 파일을 생성。HibernateTemplate를 사용하는 DAO 클래스입니다. InsertTest.java 파일을 생성를 보겠습니다. 이는 EmployeeDao 클래스의 메서드를 호출합니다.
이 예제에서는 hibernate 애플리케이션을 spring과 통합하겠습니다. spring과 hibernate 예제의 디렉토리 구조。
1、데이터베이스에서 테이블을 생성
이 예제에서는 Oracle를 데이터베이스로 사용하고 있습니다. 하지만 어떤 데이터베이스든 사용할 수 있습니다. 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
이것은 간단한 POJO 클래스입니다. 여기서, 이는 휴면하는 영구 클래스로 사용됩니다.
package com.w;3codebox; public class Employee { private int id; private String name; private float salary; //getters and setters }
3、employee.hbm.xml
이 맵핑 파일은 모든 영구 클래스 정보를 포함하고 있습니다.
<?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>
4EmployeeDao.java
이는 HibernateTemplate Employee 클래스 객체를 영구 저장하는 Java 클래스의 클래스 메서드입니다。
package com.w;3codebox; 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; } }
5applicationContext.xml
이 파일에서 우리는 BasicDataSource 객체는 데이터베이스의 모든 정보를 제공합니다. 이 객체는 사용됩니다. LocalSessionFactoryBean 객체, mappingResources와 hibernateProperties와 같은 추가 정보를 포함하고 있습니다. LocalSessionFactoryBean 의 객체는 HibernateTemplate 클래스에서 사용됩니다. applicationContext.xml 파일의 코드를 확인해 보겠습니다.
파일: 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.Oracle<9Dialect</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
이 클래스는 EmployeeDao 객체를 사용하며 Employee 객체를 전달하여 saveEmployee 메서드를 호출합니다.
package com.w;3codebox; 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); } }
지금, oracle 데이터베이스에서 해당 테이블을 볼 수 있다면, 레코드가 성공적으로 입력되었습니다.
applicationContext.xml 파일에서 hibernate 속성을 활성화할 수 있습니다. 예를 들어 hbm을 통해:2ddl.auto와 같은 옵션을 통해 자동 테이블 생성을 보여주세요. 코드를 보겠습니다:
<property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle<9Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props>
이 코드를 작성하면 테이블을 생성하지 않아도 됩니다. 자동으로 테이블이 생성됩니다.