2014년 1월 29일 수요일

스프링, 하이버네이트예제(SpringFramework, Hibernate, Oracle, HQL select, 하이버네이트매핑),구로디지털하이버네이트강좌교육 아래 실습에서 사용되는 XML파일들은 모두 src/main/...

 스프링, 하이버네이트예제(SpringFramework, Hibernate, Oracle, HQL select, 하이버네이트매핑),구로디지털하이버네이트강좌교육
 
 아래 실습에서 사용되는 XML파일들은 모두 src/main/resources 아래에 만들었음.

 1. 이클립스에서 하이버네이트 유틸리티 프로젝트 나 간단히 스프링프로젝트 하나 만들자.
 프로젝트 전체 모양은 아래와 같다

.
 
 

2. pom.xml
은 다음과 같다.
 
<?xml version="1.0" encoding="UTF-8"?>:namespace prefix = o />
<project xmlns="http://maven.apache.org/POM/4.0.0"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <modelVersion>4.0.0</modelVersion>
       <groupId>org.springframework.samples.spring</groupId>
       <artifactId>spring-hibernate-utility</artifactId>
       <version>1.0.0.CI-SNAPSHOT</version>
       <packaging>jar</packaging>
       <name>Spring HibernateUtility</name>
       <url>http://www.springframework.org</url>
       <description>
             <![CDATA[This projectis a minimal jar utility with Spring configuration for Hibernate.]]>
       </description>
       <properties>
             <maven.test.failure.ignore>true</maven.test.failure.ignore>
             <spring.framework.version>3.0.6.RELEASE</spring.framework.version>
       </properties>
 
       <dependencies>
 
             <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <version>3.6.0.Final</version>
             </dependency>
             <dependency>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                    <version>4.7</version>
                    <scope>test</scope>
             </dependency>
             <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                    <version>${spring.framework.version}</version>
             </dependency>
             <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                    <version>${spring.framework.version}</version>
             </dependency>
             <dependency>
                    <groupId>com.h2database</groupId>
                    <artifactId>h2</artifactId>
                    <version>1.3.156</version>
             </dependency>
             <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-orm</artifactId>
                    <version>${spring.framework.version}</version>
             </dependency>
             <!-- <dependency> <groupId>hsqldb</groupId><artifactId>hsqldb</artifactId>
                    <version>1.8.0.10</version></dependency> -->
             <dependency>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                    <version>1.2.16</version>
             </dependency>
             <dependency>
                    <groupId>com.oracle</groupId>
                    <artifactId>ojdbc6</artifactId>
                    <version>11.1.0.7.0</version>
             </dependency>
       </dependencies>
 
       <build>
             <plugins>
                    <plugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-compiler-plugin</artifactId>
                           <version>2.3.2</version>
                           <configuration>
                                 <source>1.5</source>
                                 <target>1.5</target>
                           </configuration>
                    </plugin>
             </plugins>
       </build>
       <repositories>
             <repository>
                    <id>oracle</id>
                    <name>ORACLE JDBCRepository</name>
                    <url>http://maven.jahia.org/maven2</url>
             </repository>
       </repositories>
 
 
 
</project>
 
 
 
3. onj.edu.hibernate.model  클래스
 
[MyEmp.java]
 
 
package onj.edu.hibernate.model;
 
import java.io.Serializable;
 
//myemp 테이블의 도메인 클래스
public class MyEmp implementsSerializable{
 
       private static final long serialVersionUID = 1L;
      
       private int empno;
       private String ename;
 
       public int getEmpno() {
             return empno;
       }
 
       public void setEmpno(int empno) {
             this.empno = empno;
       }
 
       public StringgetEname() {
             return ename;
       }
 
       public void setEname(String ename) {
             this.ename = ename;
       }
}
 
 
4. 다은은 BusinessObject 클래스를 만들자
 
 
[MyEmpBo.java]
 
package onj.edu.hibernate.bo;
 
import onj.edu.hibernate.model.MyEmp;
 
public interface MyEmpBo {
       // empno key 데이터 selcet
       public MyEmpgetMyEmp(int empno);
 
       // insert
       public void setMyEmp(MyEmp myEmp);
 
       // update
       public void updateMyEmp(MyEmp myEmp);
 
       // 이름으로 데이터 select
       public MyEmpfindEmpByName(String name);
}
 
 
 
[MyEmpBoImpl.java]
 
package onj.edu.hibernate.bo;
 
import onj.edu.hibernate.dao.MyEmpDao;
import onj.edu.hibernate.model.MyEmp;
 
public class MyEmpBoImpl implements MyEmpBo{
           MyEmpDaomyEmpDao;
          
           publicvoid setMyEmpDao(MyEmpDao myEmpDao) {
                     this.myEmpDao= myEmpDao;
           }
 
           publicMyEmp getMyEmp(int empno) {                
                     returnmyEmpDao.getMyEmp(empno);
           }
 
           publicvoid setMyEmp(MyEmp myEmp) {
                     myEmpDao.setMyEmp(myEmp);
           }
 
           publicvoid updateMyEmp(MyEmp myEmp) {
                     myEmpDao.updateMyEmp(myEmp);
           }
          
           publicMyEmp findEmpByName(String name) {
                     returnmyEmpDao.findEmpByName(name);
           }         
}
 
 
5. Data Access Object(DAO) 관련 클래스
 
[MyEmpDao.java]
 
package onj.edu.hibernate.dao;
 
import onj.edu.hibernate.model.MyEmp;
 
public interface MyEmpDao {
   //empno key 데이터 selcet
   public MyEmp getMyEmp(int empno);
   //insert
   public void setMyEmp(MyEmp myEmp);           
   //update
   public void updateMyEmp(MyEmp myEmp);
   //이름으로 데이터 select
   public MyEmp findEmpByName(String name);
}
 
 
 
 
[MyEmpDaoImpl.java]
 
package onj.edu.hibernate.dao;
 
import java.util.List;
 
import onj.edu.hibernate.model.MyEmp;
 
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
 
public class MyEmpDaoImpl extendsHibernateDaoSupport
                                     implementsMyEmpDao {
                    
           //아래에서 MyEmp.class Entity 클래스
           publicMyEmp getMyEmp(int empno) {                
                     returngetHibernateTemplate().get(MyEmp.class, empno);
           }
 
           publicvoid setMyEmp(MyEmp myEmp) {
                     getHibernateTemplate().save(myEmp);
           }
 
           publicvoid updateMyEmp(MyEmp myEmp) {
                     getHibernateTemplate().update(myEmp);
           }
          
           //주의 : 아래 from절다음의 테이블명 자리에는 실제 DB테이블명이 아니라 myemp.hbm.xml 파일의 CLASS명과 속성명이 와야한다.
           //대소문자주의!! DB의 테이블명과 컬럼명이 아님.
           //
           publicMyEmp findEmpByName(String name) {
                     Listlist  =getHibernateTemplate().find("from MyEmp where ename = ?", name);
                     return(MyEmp)list.get(0);
           }
}
 
 
6. DB테이블과 자바클래스 매핑을 위한 XML
 
[myemp.hbm.xml]
 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
       <class name="onj.edu.hibernate.model.MyEmp" table="myemp">
             <id name="empno"type="java.lang.Integer">
                    <column name="empno"/>
             </id>
             <property name="ename"type="java.lang.String">
                    <column name="ename"length="10" not-null="false"unique="false" />
             </property>
       </class>
</hibernate-mapping>
 
 
 
7. DB접속을 위한 XML 설정
 
[database.properties]
 
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.0.7:1521:onj
jdbc.username=scott
jdbc.password=tiger
 
 
[datasource.xml]
 
<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-3.2.xsd">
 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="location">
             <value>database.properties</value>
       </property>
</bean>
 
<bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
       <property name="url" value="${jdbc.url}"/>
       <property name="username" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>
</bean>
 
</beans>
 
 
 
8. 다음은 하이버네이트 관계된 설정을 하자.
 
[hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
 
<bean id="sessionFactory"
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>
 
    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
     </property>
 
     <property name="mappingResources">
       <list>
           <value>myemp.hbm.xml</value>
       </list>
      </property>   
 
    </bean>
</beans>
 
 
9. 다음은 스프링 빈 관련 설정을 하자.
 
[myemp.xml]
 
<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-3.2.xsd">
 
    <!--business object -->
   <bean id="myEmpBo" class="onj.edu.hibernate.bo.MyEmpBoImpl">
              <property name="myEmpDao"ref="myEmpDao" />
   </bean>
 
   <!--Data Access Object -->
   <bean id="myEmpDao"class="onj.edu.hibernate.dao.MyEmpDaoImpl">
              <property name="sessionFactory"ref="sessionFactory"></property>
   </bean>
</beans>
 
 
10 .지금까지 설정한 XML 파일을모으자.
 
[beanlocations.xml]
 
<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-2.5.xsd">
 
       <!--Database Configuration -->
       <import resource="datasource.xml"/>
       <import resource="hibernate.xml"/>
 
       <!--Beans Declaration -->
       <import resource="myemp.xml"/>
 
</beans>
 
 
 
11. 테스트를 위한 ClientProgram
 
package onj.edu.hibernate.client;
 
import onj.edu.hibernate.bo.MyEmpBo;
import onj.edu.hibernate.model.MyEmp;
 
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
 
public class HibernateClient
{
   public static void main( String[] args )
    {
          ApplicationContext appContext =
            newClassPathXmlApplicationContext("beanlocations.xml");
 
          MyEmpBo myEmpBo =(MyEmpBo)appContext.getBean("myEmpBo");
 
          //insert
          MyEmp myEmp = new MyEmp();
          myEmp.setEmpno(59196);
          myEmp.setEname("오라클자바");
          myEmpBo.setMyEmp(myEmp);
 
          //ename으로 select
          MyEmp myEmp2 =myEmpBo.findEmpByName("오라클자바");
          System.out.println(myEmp2);
         
          //empno select
          MyEmp myEmp3 = myEmpBo.getMyEmp(59196);
          System.out.println(myEmp2);
           
          //update
          myEmp3.setEname("OracleJava");
          myEmpBo.updateMyEmp(myEmp3);
    }
}
 
 
12. HibernateClient 를 실행
 
[결과
 
2014-01-2608:08:17,357 INFO[org.springframework.context.support.ClassPathXmlApplicationContext] -<Refreshingorg.springframework.context.support.ClassPathXmlApplicationContext@7bbfb8: startupdate [Sun Jan 26 08:08:17 KST 2014]; root of context hierarchy>
2014-01-2608:08:17,420 INFO[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <LoadingXML bean definitions from class path resource [beanlocations.xml]>
2014-01-2608:08:17,529 INFO[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <LoadingXML bean definitions from class path resource [datasource.xml]>
2014-01-2608:08:18,404 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]- <Loading XML bean definitions from class path resource [hibernate.xml]>
2014-01-2608:08:18,763 INFO[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <LoadingXML bean definitions from class path resource [myemp.xml]>
2014-01-26 08:08:19,029INFO [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] -<Loading properties file from class path resource [database.properties]>
2014-01-2608:08:19,029 INFO[org.springframework.beans.factory.support.DefaultListableBeanFactory] -<Pre-instantiating singletons inorg.springframework.beans.factory.support.DefaultListableBeanFactory@57ae46:defining beans[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,myEmpBo,myEmpDao];root of factory hierarchy>
2014-01-2608:08:19,107 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource]- <Loaded JDBC driver: oracle.jdbc.driver.OracleDriver>
SLF4J: Failed to loadclass "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting tono-operation (NOP) logger implementation
SLF4J: Seehttp://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
2014-01-2608:08:19,467 INFO [org.springframework.orm.hibernate3.LocalSessionFactoryBean]- <Building new Hibernate SessionFactory>
Hibernate: insertinto myemp (ename, empno) values (?, ?)
Hibernate: selectmyemp0_.empno as empno0_, myemp0_.ename as ename0_ from myemp myemp0_ wheremyemp0_.ename=?
onj.edu.hibernate.model.MyEmp@1c44d71
Hibernate: selectmyemp0_.empno as empno0_0_, myemp0_.ename as ename0_0_ from myemp myemp0_ wheremyemp0_.empno=?
onj.edu.hibernate.model.MyEmp@1c44d71
Hibernate: updatemyemp set ename=? where empno=?

댓글 없음:

댓글 쓰기