본문 바로가기
Programming/>> Spring

[Spring] Spring + Hibernate 설정 방법 고찰?

by 니키ᕕ( ᐛ )ᕗ 2015. 11. 24.

구글링으로 Hibernate 설정법을 찾다보면 HibernateUtil이라는 class를 만들어서 사용하는 경우가 있고 아닌 경우도 있다.



1. HibernateUtil 사용


출처 : 생활코딩 - https://opentutorials.org/module/1281/8278

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    private static String configFile = "hibernate.cfg.xml";
 
    static {
        try {
            Configuration cfg = new Configuration().configure(configFile);
            StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();
            sb.applySettings(cfg.getProperties());
            StandardServiceRegistry standardServiceRegistry = sb.build();
            sessionFactory = cfg.buildSessionFactory(standardServiceRegistry);
        } catch (Throwable th) {
            System.err.println("Enitial SessionFactory creation failed" + th);
            throw new ExceptionInInitializerError(th);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public void shutdown() {
        sessionFactory.close();
    }
}
HibernateUtil의 소스코드는 이런형태이고 3.0과 4.0의 내용이 다른걸로 알고 있다.


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://192.168.25.7:3306/DB</property> <property name="connection.username">ID</property>
<property name="connection.password">PW</property>
.... <mapping resource="/hbm/TbUser.hbm.xml"/> <mapping resource="/hbm/TbBoard.hbm.xml"/> </session-factory> </hibernate-configuration>

그리고 Hibernate.cfg.xml에 Database 연결정보가 들어간다.


@Repository
public class MemberDaoImpl implements MemberDao {
	@Override
	public List selectAll(){
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		List result = (List) session.createQuery("from TbUser").list();
		session.close();
		return result;
	}
}
아마도 DAO에 적용시키면 Singleton 형태로 되어있는 HibernateUtil의 Session을 불러올 것이다.





2. HibernateUtil X


출처 : http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annotations/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
		 
	<bean id="dataSourceMySQL" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://192.168.25.7:3306/DB"/>
		<property name="username" value="ID"/>
		<property name="password" value="PW"/>
	</bean>		
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSourceMySQL" />
		<property name="configLocation">
			<value>/WEB-INF/spring/hibernate/hibernate.cfg.xml</value>
		</property>
	</bean>
		 
	<bean id="transactionManagerMySQL" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>			 
</beans>
root-context.xml에서 DB연결정보와 sessionfactory, transaction bean을 생성


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    			....
        <mapping resource="/hbm/TbUser.hbm.xml"/>
        <mapping resource="/hbm/TbBoard.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
Hibernate.cfg.xml에는 mapping 외 순수하게 hibernate 설정이 들어간다. 굳이 부가적인 *.cfg.xml파일을 만들지 않고 root-context.xml에 설정을 다 때려박아도 되긴함..


@Repository
public class MemberDaoImpl implements MemberDao {
	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	public List<TbUser> selectAll(){
		Session session = sessionFactory.getCurrentSession();
		List<TbUser> result = (List<TbUser>) session.createQuery("from TbUser").list();
		return result;
	}
}
Dao는 이런 형태로 SessionFactory를 주입받아서 사용하게 된다.


그리고 Hibernate mapping 방법중엔 hbm.xml을 만드는 것과 annotation을 사용하는 방법이 있다.
@Entity
@Table(name="myemp")
public class MyEmp implementsSerializable{
      @Id
       @Column(name="empno", unique=true, nullable=false)
       private Integer empno;   

       @Column(name="ename", unique=false, nullable=false, length=10)
       private String ename;
     
       public Integer getEmpno() {
             return empno;
       }
 
       public void setEmpno(Integer empno) {
             this.empno = empno;
       }
       
       public StringgetEname() {
             return ename;
       }
 
       public void setEname(String ename) {
             this.ename = ename;
       }
}
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	<property name="dataSource" ref="dataSourceMySQL" />
	<property name="configLocation">
		<value>/WEB-INF/spring/hibernate/hibernate.cfg.xml</value>
	</property>
	<property name="packagesToScan">
		<list>
			<value>sample.hibernate.domain</value>
		</list>
	</property>
</bean>
Domain에 Annotation으로 table과 mapping시킨 후, spring에서 어노테이션을 읽을 수 있도록 Scan설정을 한다.



HibernateUtil방법으로는 annotation사용이 불가능한데 왜 굳이 HibernateUtil을 만들어서 사용하는지 찾아보았으나 별다른 이유를 찾지못했다.


단순히 추측하기로는 Spring을 이용하지 않고 사용하던 방법이겠고 

Hibernate의 버전이 낮았을때는 Spring과의 호환이 잘 안맞았다고 하니 그것을 극복하기 위해 나온 방법이지 않을까.. 싶음


하지만 Spring의 기본 바탕은 Inverse of Control, Dependency Injection... 등등인데 Singleton 객체를 만들어서 사용하는 것은 그것과 어울리지 않는다는 생각이 들지만

공부가 부족하니 어떤것이 맞는 거라고 정확하게 꽉 집에서 맞는거다라고 결단을 내릴 수는 없지만 그런식으로 유추해본다.


아 근데 진짜 hbm.xml과 annotation 중 어떤 것이 좋은 선택인지 모르겠다.


댓글