티스토리 뷰

카테고리 없음

hibernate vs iBatis

달리는개발자 2013. 2. 4. 15:56

iBatis 3.0 버전인 myBatis만 사용하다가 hibernate 적용에 관해 자료조사 및 적용을 해봤습니다.

hibernate와 iBatis는 성격이 달라 단순비교하는 것은 맞지 않고 해당 프로젝트의 상황에 맞게 어느 것을 사용할 지 선택하는 것이 맞다고 합니다.

 우리나라에서는 설계 후 개발 중 추가요구사항을 받다보면 초기 DB설계와 많이 달라져서 좀 더 유연한 iBatis를 선호하는 경향이 있다고 하나 토비님의 글을 읽어보면 이건 무지(無知)에서 오는 결론이 아닐까 생각합니다.

hibernate 도입에 관해서 하단의 있는 글들을 읽고 같이 고민해볼 필요가 있을 것 같습니다.

 

 

iBatis 와 hibernate 특징

iBatis : SQL Mapper

hibernate : Object Relation Mapper

 

iBatis는 단순하고 빠른 개발시간과 유연성, 작은 패키징 크기가 특징이고,

Hibernate는 SQL을 동적으로 작성해주기 때문에 쿼리를 작성에 시간을 보내지 않아도 되고 고급 캐시 알고리즘 등의 특징이 있다.

 

iBatis는 SQL에 능숙하고 적절한 튜닝이 필요할 때 사용하고, hibernate는 완전한 ORM 솔루션을 만들 때, SQL에 능숙하지 않는 개발자가 객체 지향 개발을 할때 사용한다.

 

참고

iBATIS vs Hibernate

 

myBatis에서 hibernate로 전환 방법

 

pom.xml 수정

 


   org.hibernate
   hibernate-core
   4.1.9.Final
  
 

 

hibernate.cfg.xml 추가

 






 

  
  
  
  java:comp/env/jdbc/survey

  
  1

  
  org.hibernate.dialect.MySQLInnoDBDialect

  
  

  
  org.hibernate.cache.internal.NoCacheProvider

  
  true

  
  update

  
 



 

webapps/META-INF/context.xml 추가

 



 

 

Survey.hbm.xml 추가

 





 
  
   
  
  
  
  
  
  
  
  
 

 

 

spring-servlet.xml 수정

 

dataSource 변경 전

 


  
  
  
  
  
  
  
  
 


 

 

dataSource 변경 후 

 


 

관련 bean 추가

 


  
 
 
 
  
 

 

surveyDaoImpl 수정

 

변경 전

 

/**
 *  SurveyDaoImpl.java
 *
 *	Project : SurveyAdmin
 *
 *	Copyright 2013 shuiky (www.naver.com)
 *
 *	Written by shuiky@naver.com
 * 		2013. 1. 23. first written.
 *
 *	Note:
 */
package com.shuiky.survey.admin.dao;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.shuiky.survey.admin.model.Survey;
import com.shuiky.survey.admin.model.SurveySearch;

/**
 * @author jhjeon
 *
 */
public class SurveyDaoImpl extends SqlSessionDaoSupport implements SurveyDao {
	
	@Override
	public Long countSurvey(SurveySearch surveySearch) throws Exception {
		if(surveySearch == null) return (long) 0;
		
		Object obj = getSqlSession().selectOne("SurveyMapper.selectSurveyCount", surveySearch);
		return obj == null ? 0 : (Long) obj;
	}

	
	@Override
	public List listSurvey(SurveySearch surveySearch) throws Exception {
		if(surveySearch == null) return null;
		
		return getSqlSession().selectList("SurveyMapper.selectSurveyList", surveySearch);
	}
	
	@Override
	public Survey getSurvey(long surveyId) throws Exception {
		return getSqlSession().selectOne("SurveyMapper.selectSurvey", new Survey(surveyId));
	}

}

 

변경 후

/**
 *  SurveyDaoImpl.java
 *
 *	Project : SurveyAdmin
 *
 *	Copyright 2013 shuiky 
 *
 *	Written by shuiky@naver.com
 * 		2013. 1. 23. first written.
 *
 *	Note:
 */
package com.shuiky.survey.admin.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.shuiky.survey.admin.model.Survey;
import com.shuiky.survey.admin.model.SurveySearch;

/**
 * @author jhjeon
 *
 */
@Repository
public class SurveyDaoImpl implements SurveyDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public Long countSurvey(SurveySearch surveySearch) throws Exception {
		if(surveySearch == null) return (long) 0;
		return (Long) this.sessionFactory.getCurrentSession()
				.createQuery("select count(*) from Survey")
				.uniqueResult(); 
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List listSurvey(SurveySearch surveySearch) throws Exception {
		if(surveySearch == null) return null;
		return (List) this.sessionFactory.getCurrentSession()
				.createQuery("from Survey")
				.setFirstResult((int) surveySearch.getStartRowNo())
				.setMaxResults((int) surveySearch.getPageSize())
				.list();
	}
	
	@Override
	public Survey getSurvey(long surveyId) throws Exception {
		return (Survey) this.sessionFactory.getCurrentSession()
				.byId(Survey.class)
				.getReference(surveyId);
	}

}

 

 

 

myBatis에서 hibernate로 전환 시 문제 해결

 

Not supported by BasicDataSource

 

문제

datasource를 BasicDataSource로 설정하니 오류가 발생

 


  
  
  
  
  
  
  
  
 

 

원인

BasicDataSource를 지원하지 않음

 

해결

JNDI(Java Naming and Directory Interface) 설정으로 변경

 

webapps 디렉토리 밑에 META-INF 디렉토리 생성 후 context.xml 추가

 

 



 

 

 

 

참고

http://wiki.apache.org/tomcat/TomcatHibernate

 

 

org.hibernate.hql.internal.ast.QuerySyntaxException: sv_survey is not mapped [from sv_survey]

 

문제

Dao에 쿼리문 생성 시 아래와 같이 작성하였더니 오류 발생

 

@Override
 public Long countSurvey(SurveySearch surveySearch) throws Exception {
  if(surveySearch == null) return (long) 0;
  return (Long) this.sessionFactory.getCurrentSession()
    .createQuery("select count(*) from sv_survey")
    .uniqueResult(); 
 } 

 

원인

HQL(Hibernate Query Language) 에서는 실제 테이블의 정보가 아니라 매핑되는 java class 명과 property 명을 사용해야됨

 

해결

@Override
public Long countSurvey(SurveySearch surveySearch) throws Exception {
if(surveySearch == null) return (long) 0;
return (Long) this.sessionFactory.getCurrentSession()
.createQuery("select count(*) from Survey")
.uniqueResult(); 
}

 

 

참고

http://stackoverflow.com/questions/9954590/hibernate-error-querysyntaxexception-users-is-not-mapped-from-users

 

 

 

hibernate FAQ 에 있는대로 쿼리 결과를 count해서 가져오려고 했더니 ClassCastException 발생

 

문제

Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();

실행하니 아래와 같은 오류 발생

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

 

원인

FAQ 버그로 보인다....?

 

해결

Long count = (Long) session.createQuery("select count(*) from ....").uniqueResult();

 

참고

https://forum.hibernate.org/viewtopic.php?p=2408648

 

 

org.hibernate.HibernateException: createQuery is not valid without active transaction

 

문제

샘플 hibernate.cfg.xml 설정을 복사해서 작업하던 중 오류

 

원인

hibernate.cfg.xml 설정 중 다음 항목 때문에 발생

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

 

해결

설정 해제

<!-- Enable Hibernate's automatic session context management -->
<!--property name="current_session_context_class">thread</property-->

 

참고

http://stackoverflow.com/questions/11305979/transactionalspringhibernate-doesnt-work

 

 

참고

 

Hibernate Documentation

http://www.hibernate.org/docs

 

Hibernate FAQ

https://community.jboss.org/en/hibernate/faq

 

Hibernate HQL Select statement exmples

http://camelcode.org/tutorial/Hibernate-HQL-Select-statement-examples.htm

 

Hibernate Query Examples(HQL)

http://www.mkyong.com/hibernate/hibernate-query-examples-hql/

 

Hibernate VS iBatis 이건 기술적인 문제가 아니다.

http://zeous.egloos.com/2122663

 

iBatis vs Hibernate

http://s-xu.blogspot.kr/2011/03/ibatis-vs-hibernate.html

 

Hibernate VS iBATIS

http://dotnetpower.tistory.com/49

 

 

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함