Spring4MVC,Hibernate4연동예제(Spring MVC,이클립스Luna,@Transactional, Oracle11g, Java7, Tomcat7, 스프링4하이버네이트4연동예제소스),오라클자바커뮤니티실무교육
[실습버전]
Java 7
Eclipse 4.4 Luna
Spring framework 4.0.2.RELEASED
Hibernate ORM 4.3.5.Final
Tomcat 7
이클립스 프로젝트 구성은 아래 그림과 같다.
1. 테스트를 위한 Table생성
create table myemp
(empno number primary key,
ename varchar2(100),
addr varchar2(100)
);
SQL> insert into myemp values (1, '1길동','서울 1가');
SQL> insert into myemp values (3, '2길동','서울 3가');
SQL> insert into myemp values (5, '5길동','서울 5가');
SQL> insert into myemp values (2, '오라클자바커뮤니티','서울 구로구 구로동 ');
2. File -> New -> Project -> Spring -> Spring Project -> Simple Spring Web Maven
project name은 spring4hibernate로 하자.(웹사이트 컨텍스트 이름은 자동으로 spring4hibernate가 된다.)
3. pom.xml에서 스프링 버전을 4.0.2로, 하이버네이트 버전을 4.3.5로 변경하자.
<spring-framework.version>4.0.2.RELEASE</spring-framework.version>
<hibernate.version>4.3.5.Final</hibernate.version>
그리고 oracle 관련 dependency 및 repository 추가
그런다음 프로젝트에서 마우스 우측버튼 -> maven -> update project를 실행하여 spring4 관련 jar 파일을 내려받자.
pom.xml은 아래와 같다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.service.service</groupId>
<artifactId>spring4hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>4.0.2.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.3.5.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oracle</id>
<name>ORACLE JDBCRepository</name>
<url>http://maven.jahia.org/maven2</url>
</repository>
</repositories>
</project>
4. 하이버네이트 매핑을 위한 모델쪽 클래스를 만들자.
(MyEmp.java)
//myemp 테이블에 매핑되는 Domain Model Class
package model;
public class MyEmp {
private int empno;
private String ename;
private String addr;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
5. 모델클래스와 매핑을 위한 하이버네이트 XML 매핑
(src/main/resources/myemp.hbm.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 모델쪽의 MyEmp 클래스와 테이블 MYEMP를 매핑한다. -->
<hibernate-mapping package="model">
<class name="MyEmp" table="MYEMP">
<id name="empno" column="empno">
</id>
<property name="ename" column="ename" />
<property name="addr" column="addr" />
</class>
</hibernate-mapping>
6. 하이버네이트 XML 설정 파일
(hibernate.cfg.xml)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- 하이버네이트 설정 파일 -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping resource="myemp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7. 이번에는 DAO쪽 인터페이스, 클래스를 만들자.
(MyEmpDao.java)
package dao;
import java.util.List;
import model.MyEmp;
public interface MyEmpDao {
public List<MyEmp> list();
}
(MyEmpDaoImpl.java)
아래에서 하이버네이트의 SessionFactory가 생성자 주입되며, list 메소드에서 DB에 쿼리 후
결과 데이터를 받아서 List형태로 되 돌린다. 그리고 list 메소드에는 @Transactional 어노테이션으로
트랜잭션에 참가하고 있음을 알 수 있다.
package dao;
import java.util.List;
import javax.transaction.Transactional;
import model.MyEmp;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
public class MyEmpDaoImpl implements MyEmpDao {
private SessionFactory sessionFactory;
public MyEmpDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public List<MyEmp> list() {
@SuppressWarnings("unchecked")
List<MyEmp> list = (List<MyEmp>)sessionFactory.getCurrentSession()
.createCriteria(MyEmp.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return list;
}
}
8. 이번에는 디스패처 서블릿의 설정 파일을 작성하자.
(/WEB-INF/mvc-config.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="controller"/>
<mvc:annotation-driven />
<!-- 뷰 리졸버 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DB접근을 위한 DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url"><value>jdbc:oracle:thin:@localhost:1521:onj</value></property>
<property name="username"><value>scott</value></property>
<property name="password"><value>tiger</value></property>
</bean>
<!-- 하이버네이트 세션을 위한 세션팩토리 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<!-- 하이버네이트 트랜잭션을 위한 TransactionManager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myEmpDao" class="dao.MyEmpDaoImpl">
<!-- 생성자 주입 -->
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
</beans>
9. 컨트롤러 작성
package controller;
import java.util.List;
import model.MyEmp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import dao.MyEmpDao;
@Controller
public class OracleJavaController {
//DAO클래스가 자동 주입된다.
@Autowired
private MyEmpDao myEmpDao;
//URL요청시 아래와 같이 해야 한다.
//http://localhost:8080/spring4hibernate/hibernate4
@RequestMapping(value="/hibernate4")
public String doAction(ModelMap model) {
List<MyEmp> list = myEmpDao.list();
model.addAttribute("emplist", list);
return "oraclejavacommunity";
}
}
10. 뷰 역할을 하는 JSP작성
(/WEB-INF/view/oraclejavacommunity.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="utf-8">
<title>MyEmp List</title>
</head>
<body>
<div align="center">
<h1>ORACLEJAVA CONNUMITY EMP LIST</h1>
<table boarder="1">
<th>empno</th>
<th>ename</th>
<th>addr</th>
<c:forEach var="myemp" items="${emplist}" varStatus="status">
<tr>
<td>${myemp.empno}</td>
<td>${myemp.ename}</td>
<td>${myemp.addr}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
11. web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>spring4hibernate</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
12. 실행
http://localhost:8080/spring4hibernate/hibernate4
평일주간[100%환급과정]
(8/25)C#4.0,WinForm,ADO.NET
(8/25)안드로이드개발자과정
(8/25)SQL기초에서 Schema Object까지
(8/29)Spring,MyBatis,Hibernate실무과정
(8/29)자바기초JDBC,Servlet/JSP까지
(8/29)PL/SQL,ORACLE HINT,TUNING
(8/25)오라클자바채용확정교육
평일야간[개인80%환급]
(8/21)Spring, MyBatis, Hibernate
(8/21)HTML5,CSS3,Ajax,jQuery마스터
(8/21)C#,Network,ADO.NET,ASP.NET
(8/26)SQL기초에서실무까지
(8/26)안드로이드개발자과정
(8/28)자바JSP,jQuery,Spring,MyBatis
주말주간[개인80%환급]
(8/23)자바웹&스프링,마이바티스
(8/23)Spring, MyBatis, Hibernate
(8/23)SQL기초에서실무까지
(8/23)자바,네트워크,웹&스프링
(8/30)안드로이드개발자과정
(8/30)C#,ASP.NET마스터(8/30)웹퍼블리싱 마스터
주말야간[개인80%환급]
(8/23)SQL기초에서실무까지
(8/23)자바,네트워크,웹&스프링
(8/25)안드로이드개발자과정
(8/25)SQL기초에서 Schema Object까지
(8/29)Spring,MyBatis,Hibernate실무과정
(8/29)자바기초JDBC,Servlet/JSP까지
(8/29)PL/SQL,ORACLE HINT,TUNING
(8/25)오라클자바채용확정교육
평일야간[개인80%환급]
(8/21)Spring, MyBatis, Hibernate
(8/21)HTML5,CSS3,Ajax,jQuery마스터
(8/21)C#,Network,ADO.NET,ASP.NET
(8/26)SQL기초에서실무까지
(8/26)안드로이드개발자과정
(8/28)자바JSP,jQuery,Spring,MyBatis
주말주간[개인80%환급]
(8/23)자바웹&스프링,마이바티스
(8/23)Spring, MyBatis, Hibernate
(8/23)SQL기초에서실무까지
(8/23)자바,네트워크,웹&스프링
(8/30)안드로이드개발자과정
(8/30)C#,ASP.NET마스터(8/30)웹퍼블리싱 마스터
주말야간[개인80%환급]
(8/23)SQL기초에서실무까지
(8/23)자바,네트워크,웹&스프링
댓글 없음:
댓글 쓰기