Hibernate Service

HibernateService는 Hibernate libraries에 대한 wrapper로써, 본 페이지에서는 Hibernate api, JDBC api를 조합하여 HibernateService 사용 방법을 가이드하고자 한다. HibernateService 서비스에 대한 Wrapper는 1가지이며, 다음과 같다. ※ 현재 Anyframe 3.0.1 버전에서는 아래의 서비스에 대해 제공하지 않고 있으며, 향후 2008년 9월(예정) 배포될 Anyframe 3.1 버전에서 Hibernate에 대한 세부 가이드를 다시 제공할 예정이다.

CommonService

Common Service는 RDBMS operations(C/R/U/D)를 간단화하는 Hibernate의 wrapper service이다. 이를 이용함으로써 중복적인 jdbc와 hibernate api 호출을 제거할 수 있다. 이 서비스를 사용하기 위해서 다음과 같은 3 종류의 configuration이 필요하다.
  • SessionFactory

  • 다음은 Hibernate SessionFactory Bean 정의시 필요한 설정 정보이다.
    Property Name
    Description
    Required
    Default Value
    dataSource datasource service를 참조하기 위한 bean id 정의
    Y
    N/A
    mappingDirectoryLocations hibernate 매핑 정의 파일의 location. 절대 / 상대 물리적인 파일 경로 지정 방법과 Classpath를 이용한 지정 방법 2가지가 있다
    N
    N/A
    hibernateProperties hibernate engine을 초기화 하기 위한 hibernate properties
    Y
    N/A

  • LookupHibernate

  • 다음은 Lookup Object 정의시 필요한 설정 정보이다.
    Property Name
    Description
    Required
    Default Value
    sessionFactory hibernate session factory를 참조하기 위한 bean id
    Y
    N/A

  • CommonDAOHibernate

  • 다음은 Common DAO 정의시 필요한 설정 정보이다.
    Property Name
    Description
    Required
    Default Value
    sessionFactory hibernate session factory 참조하기 위한 bean id
    Y
    N/A

    위 3종류의 속성을 기반으로 비로소 CommonService를 정의할 수 있다.
    다음은 CommonService 정의시 필요한 설정 정보이다.
    Property Name
    Description
    Required
    Default Value
    commonDAO commonDAO bean을 참조하기 위한 bean id
    Y
    N/A
    lookupObject lookupObject bean을 참조하기 위한 bean id
    Y
    N/A

Samples

다음은 CommonService의 속성 설정 및 테스트 코드에 대한 예제이다.
  • SessionFactory Configuration
  • 다음은 datasource와 hibernate 매핑 정의 파일의 location 등을 정의한 applicationContext-hibernate.xml의 SessionFactory 정의 부분이다. SessionFactory Bean은 HSQL DB 기반의 common_datasource를 이용하여 Connection 객체를 구하며, hibernate 매핑 파일은 클래스패스 hibernate상에서 찾게 된다.
    <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="common_datasource" />
        <property name="mappingDirectoryLocations">
            <value>classpath:/hibernate</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</prop> 
                <prop key="hibernate.cache.use_second_level_cache">true</prop> 
            </props>
        </property>
    </bean>
    다음은 위 SessionFactory에서 참조하고 있는 Hibernate mapping 파일인 User.hbm.xml 파일의 일부이다. 테이블 USERS와 클래스 integration.anyframe.services.hibernate.vo.UserVO 사이의 매핑 정보를 담고 있음을 알 수 있다. 보다 자세한 mapping 파일 정의를 위해서는 Hibernate Reference Documentation - Mapping declaration을 참조하도록 한다.
    <hibernate-mapping package="integration.anyframe.services.hibernate.vo">
        <class name= "UserVO" table="USERS">
            <id name="userId" column="USER_ID" type="string">
                <generator class="assigned"/>
            </id>
            <property name="userName" 	column="USER_NAME" not-null="true"/>
            <property name="password"   column="PASSWORD" not-null="true" update="false"/>
            <property name="role"     	column="ROLE" update="false"/>
            <property name="ssn"    	column="SSN" />
            <property name="slYn"   	column="SL_YN"/>
            <property name="birthDay"   column="BIRTH_DAY"/>
            <property name="age"   		column="AGE"/>
            <property name="cellPhone"  column="CELL_PHONE"/>
            <property name="addr"   	column="ADDR"/>
            <property name="email"   	column="EMAIL"/>
            <property name="emailYn"   	column="EMAIL_YN"/>
            <property name="imageFile"  column="IMAGE_FILE" update="false"/>        
            <property name="regDate"   	column="REG_DATE" update="false"/>
        </class>
    </hibernate-mapping>
    다음은 위의 hbm.xml파일에 정의된 UserVO.java 파일의 일부이다. UserVO 클래스는 테이블 USERS의 칼럼과 매핑되는 attributes와 각 attribute에 대한 getter, setter로 구성된다.
    public class UserVO {
    	private String userId;
    
        private String userName;
    
        private String password;
    
        private String role;
    
        private String ssn;
    
        private String slYn;
    
    	....
    }
  • LookupHibernate Configuration
  • 다음은 LookupHibernate에 대한 속성 정의 예제이다. 앞서 정의한 sessionFactory Bean을 참조하고 있다.
    <bean id="lookupObject" class="anyframe.core.hibernate.impl.LookupHibernate">
        <property name="sessionFactory" ref="sessionFactory" /></bean>
  • CommonDAOHibernate Configuration
  • 다음은 CommonDAOHibernate에 대한 속성 정의 예제이다. 앞서 정의한 sessionFactory Bean을 참조하고 있다.
    <bean id="commonDAO" class="anyframe.core.hibernate.impl.CommonDAOHibernate">
        <property name="sessionFactory" ref="sessionFactory" /></bean>
  • CommonService Configuration
  • 다음은 CommonDAOHibernate, LookupHibernate을 이용한 CommonService 속성 정의 예제이다.
    <bean class="anyframe.core.hibernate.impl.CommonService">
         <property name="commonDAO" ref="commonDAO"/>     <property name="lookupObject" ref="lookupObject"/></bean>
  • TestCase
  • 다음은 앞서 정의한 속성 설정을 기반으로 hibernateService를 이용하여 데이터를 추가,삭제,수정하는 HibernateServiceTest.java 코드의 일부이다.
    데이터 추가를 위한 예제 코드는 다음과 같다.
    /**
     * data를 inser하기위한 testcase
     */
    public void testInsert() throws Exception {
    	ICommonService hibernateService = (ICommonService) context
    			.getBean("hibernateService");
    	// 1. VO객체에 데이터를 셋팅한다.
    	UserVO userVO = new UserVO();
    	userVO.setUserId("admin");
    	userVO.setUserName("gang");
    	userVO.setPassword("gang");
    	userVO.setRole("user");
    	userVO.setSsn("1234567890");
    	userVO.setSlYn("Y");
    	userVO.setBirthDay("19750319");
    	userVO.setAge(null);
    	userVO.setCellPhone("1234567890");
    	userVO.setAddr("kamala road");
    	userVO.setEmail("ga@samsung.com");
    	userVO.setEmailYn("y");
    	userVO.setImageFile("ga");
    	userVO.setRegDate(null);
    	// 2.userVO를 저장한다.	
    	hibernateService.saveObject(userVO);	// 3.testSelect()를 호출해서 방금 저장한 데이터의 존재 유무를 확인한다.	
    	UserVO result = testSelect();
    	if (result == null)
    		throw new Exception("fail add");
    }
    데이터의 수정을 위한 예제 코드는 다음과 같다.
    /**
     * data를 update하기위한 testcase
     */
    public void testUpdate() throws Exception {
    	ICommonService hibernateService = (ICommonService) context
    			.getBean("hibernateService");
    	// 1. VO객체에 데이터를 셋팅한다.
    	UserVO userVO = new UserVO();
    	userVO.setUserId("admin");
    	userVO.setUserName("gang");
    	userVO.setPassword("gang");
    	userVO.setRole("user");
    	userVO.setSsn("1234567890");
    	userVO.setSlYn("Y");
    	userVO.setBirthDay("19750319");
    	userVO.setAge(null);
    	userVO.setCellPhone("0987654321");
    	userVO.setAddr("kamala road");
    	userVO.setEmail("ga@samsung.com");
    	userVO.setEmailYn("y");
    	userVO.setImageFile("ga");
    	userVO.setRegDate(null);
    	// 2. userVO객체를 업데이트 한다.	
    	hibernateService.updateObject(userVO);	//3. testSelect()를 호출해서 데이터가 업데이트 됐는지 테스트한다.	
    	UserVO result = testSelect();
    	if (!result.getCellPhone().equals(userVO.getCellPhone()))
    		throw new Exception("fail update");
    }
    데이터의 삭제를 위한 예제 코드는 다음과 같다.
    /**
     * data를 remove하기위한 testcase
     */
    public void testRemove() throws Exception {
    	ICommonService hibernateService = (ICommonService) context
    			.getBean("hibernateService");
    	// 1.id값이 'admin'인 object를 삭제한다.
    	hibernateService.removeObject(UserVO.class, "admin");	// 2.testSelect()를 호출하여 삭제한 object가 null인지 테스트한다.	
    	UserVO userVO = testSelect();
    	if(userVO!=null)
    		throw new Exception("fail removeObject");
    }
    테스트를 위해 입력된 데이터를 추출해주는 예제 코드는 다음과 같다.
    /**
     * 입력된 데이터를 추출하기 위한 메소드
     */
    private UserVO testSelect() throws Exception {
    	ICommonService hibernateService = (ICommonService) context
    			.getBean("hibernateService");
    	try {
    		return (UserVO) hibernateService.getObject(UserVO.class, "admin");	} catch (ObjectRetrievalFailureException e) {
    		return null;
    	}
    }

Resources