2014년 2월 3일 월요일

스프링, 하이버네이트애노테이션예제(SpringFramework, Hibernate Annotation, Oracle, HQL select, 하이버네이트매핑), 오라클자바커뮤니티,오엔제이

스프링, 하이버네이트애노테이션예제(SpringFramework, Hibernate Annotation, Oracle, HQL select, 하이버네이트매핑), 오라클자바커뮤니티,오엔제이 스프링강좌교육
 
아래 실습에서 사용되는 XML파일들은 모두 src/main/resources 아래에 만들었음.
 
이전 스프링, 하이버네이트 예제와 크게 다른 점은
<!--[if !supportLists]-->-      <!--[endif]-->자바파일에 Annotation을 이용하여 작성(Entity Class MyEmp.java 파일이 많이 바뀜)
<!--[if !supportLists]-->-      <!--[endif]-->XML파일(myemp.hmb.xml,myemp.xml 파일 삭제됨)
<!--[if !supportLists]-->-      <!--[endif]-->Hibernate xml 파일의 sessionFactory 클래스 파일이 AnnotationSessionFactoryBean으로 바뀜
    Beanlocations.xmlcontext:component-scan 패키지 경로 추가
 
 
1. 이클립스에서 하이버네이트 유틸리티 프로젝트 나 간단히 스프링프로젝트 하나 만들자.
 
프로젝트 전체 모양은 아래와 같다.
 


 
2. pom.xml은 다음과 같다.
 
 
<?xml version="1.0" encoding="UTF-8"?>
<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.2.3.RELEASE</spring.framework.version>
       </properties>
 
       <dependencies>
 
             <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <version>3.5.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>
             <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-log4j12</artifactId>
             <version>1.5.8</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;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
 
//myemp 테이블의 도메인 클래스
@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;
       }
}
 
 
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;
 
importorg.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service("myEmpBo")
public class MyEmpBoImpl implements MyEmpBo {
       @Autowired
       MyEmpDao myEmpDao;
      
       public void setMyEmpDao(MyEmpDao myEmpDao) {
             this.myEmpDao = myEmpDao;
       }
 
       public MyEmpgetMyEmp(int empno) {           
             return myEmpDao.getMyEmp(empno);
       }
 
       public void setMyEmp(MyEmp myEmp) {
             myEmpDao.setMyEmp(myEmp);
       }
 
       public void updateMyEmp(MyEmp myEmp) {
             myEmpDao.updateMyEmp(myEmp);
       }
      
       public MyEmpfindEmpByName(String name) {
             return myEmpDao.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);
}
 
[MyEmpHibernateDaoSupport.java]
 
 
package onj.edu.hibernate.util;
 
import org.hibernate.SessionFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
 
//Annotation Mode에서 DAO클래스가 직접HibernateDaoSupport 상속받는것은 불가능
//DAO에서 sessionFactory bean Autowired하는것은 불가능
public abstract class MyEmpHibernateDaoSupport extends HibernateDaoSupport
{   
    @Autowired
    public void anyMethodName(SessionFactorysessionFactory)
    {
        setSessionFactory(sessionFactory);
    }
}
 
 
 
[MyEmpDaoImpl.java]
 
package onj.edu.hibernate.dao;
 
import java.util.List;
 
import onj.edu.hibernate.model.MyEmp;
importonj.edu.hibernate.util.MyEmpHibernateDaoSupport;
import org.springframework.stereotype.Repository;
 
 
//Annotation Mode에서 DAO클래스가 직접HibernateDaoSupport 상속받는것은 불가능
//DAO에서 sessionFactory bean Autowired하는것은 불가능
@Repository("myEmpDao")
public class MyEmpDaoImpl extendsMyEmpHibernateDaoSupport
                                     implements MyEmpDao {
            
       //아래에서 MyEmp.class Entity 클래스
       public MyEmpgetMyEmp(int empno) {           
             return getHibernateTemplate().get(MyEmp.class, empno);
       }
 
       public void setMyEmp(MyEmp myEmp) {
             getHibernateTemplate().save(myEmp);
       }
 
       public void updateMyEmp(MyEmp myEmp) {
             getHibernateTemplate().update(myEmp);
       }
      
       //주의 : 아래 from절다음의 테이블명 자리에는 실제 DB테이블명이 아니라 myemp.hbm.xml 파일의 CLASS명과 속성명이 와야한다.
       //대소문자 주의!! DB 테이블명과 컬럼명이 아님.
       //
       public MyEmpfindEmpByName(String name) {
             List list  = getHibernateTemplate().find("from MyEmp where ename = ?", name);
             return(MyEmp)list.get(0);
       }
}
 
 
 
 
6. 다음은 하이버네이트 관계된 설정을 하자.
 
[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.annotation.AnnotationSessionFactoryBean">
 
    <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>
 
 <!-- 
     <propertyname="mappingResources">
       <list>
          <value>myemp.hbm.xml</value>
       </list>
      </property>   
 -->
 <property name="annotatedClasses">
       <list>
           <value>onj.edu.hibernate.model.MyEmp</value>
       </list>
      </property>
   
    </bean>
</beans>
 
7. 다음은 데이터베이스 관련 설정을 하자.
 
[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 .지금까지 설정한 XML 파일을모으자.
 
[beanlocations.xml]
 
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
       <!-- DatabaseConfiguration -->
       <import resource="datasource.xml"/>
       <import resource="hibernate.xml"/>
      
       <!--Auto scan the components -->
       <context:component-scan base-package="onj.edu.hibernate.dao,onj.edu.hibernate.bo" />
 
</beans>
 
9. 테스트를 위한 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(59192);
          myEmp.setEname("오라클자바");
          myEmpBo.setMyEmp(myEmp);
 
          //ename으로 select
          MyEmp myEmp2 =myEmpBo.findEmpByName("오라클자바");
          System.out.println(myEmp2);
         
          //empno select
          MyEmp myEmp3 = myEmpBo.getMyEmp(59192);
          System.out.println(myEmp2);
           
          //update
          myEmp3.setEname("OracleJava");
          myEmpBo.updateMyEmp(myEmp3);
    }
}
 
10. HibernateClient 를 실행
 
[결과
2014-01-2612:21:45,826 INFO[org.springframework.context.support.ClassPathXmlApplicationContext] -<Refreshingorg.springframework.context.support.ClassPathXmlApplicationContext@46a09b:startup date [Sun Jan 26 12:21:45 KST 2014]; root of context hierarchy>
2014-01-2612:21:45,888 INFO[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <LoadingXML bean definitions from class path resource [beanlocations.xml]>
2014-01-2612:21:46,013 INFO[org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - <LoadingXML bean definitions from class path resource [datasource.xml]>
2014-01-2612:21:46,045 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]- <Loading XML bean definitions from class path resource [hibernate.xml]>
2014-01-2612:21:46,248 INFO[org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] -<Loading properties file from class path resource [database.properties]>
2014-01-2612:21:46,263 INFO[org.springframework.beans.factory.support.DefaultListableBeanFactory] -<Pre-instantiating singletons inorg.springframework.beans.factory.support.DefaultListableBeanFactory@143b598:defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sessionFactory,myEmpDao,myEmpBo,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];root of factory hierarchy>
2014-01-2612:21:46,357 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource]- <Loaded JDBC driver: oracle.jdbc.driver.OracleDriver>
2014-01-2612:21:46,404 INFO [org.hibernate.cfg.annotations.Version] - <HibernateAnnotations 3.5.0-Final>
2014-01-2612:21:46,420 INFO [org.hibernate.cfg.Environment] - <Hibernate3.5.0-Final>
2014-01-2612:21:46,420 INFO [org.hibernate.cfg.Environment] - <hibernate.propertiesnot found>
2014-01-2612:21:46,435 INFO [org.hibernate.cfg.Environment] - <Bytecode provider name: javassist>
2014-01-2612:21:46,435 INFO [org.hibernate.cfg.Environment] - <using JDK 1.4java.sql.Timestamp handling>
2014-01-2612:21:46,513 INFO [org.hibernate.annotations.common.Version] - <HibernateCommons Annotations 3.2.0.Final>
2014-01-2612:21:46,560 INFO [org.hibernate.cfg.AnnotationBinder] - <Binding entityfrom annotated class: onj.edu.hibernate.model.MyEmp>
2014-01-2612:21:46,607 INFO [org.hibernate.cfg.annotations.EntityBinder] - <Bindentity onj.edu.hibernate.model.MyEmp on table myemp>
2014-01-2612:21:46,638 INFO [org.hibernate.cfg.AnnotationConfiguration] - <HibernateValidator not found: ignoring>
2014-01-2612:21:46,638 INFO [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean]- <Building new Hibernate SessionFactory>
2014-01-2612:21:46,638 INFO[org.hibernate.cfg.search.HibernateSearchEventListenerRegister] - <Unable tofind org.hibernate.search.event.FullTextIndexEventListener on the classpath.Hibernate Search is not enabled.>
2014-01-2612:21:46,701 INFO [org.hibernate.connection.ConnectionProviderFactory] -<Initializing connection provider:org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider>
2014-01-2612:21:47,607 INFO [org.hibernate.cfg.SettingsFactory] - <RDBMS: Oracle,version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With thePartitioning, OLAP, Data Mining and Real Application Testing options>
2014-01-2612:21:47,607 INFO [org.hibernate.cfg.SettingsFactory] - <JDBC driver: OracleJDBC driver, version: 11.1.0.7.0-Production>
2014-01-2612:21:47,623 INFO [org.hibernate.dialect.Dialect] - <Using dialect:org.hibernate.dialect.Oracle10gDialect>
2014-01-2612:21:47,638 INFO [org.hibernate.transaction.TransactionFactoryFactory] -<Transaction strategy:org.springframework.orm.hibernate3.SpringTransactionFactory>
2014-01-2612:21:47,638 INFO [org.hibernate.transaction.TransactionManagerLookupFactory] -<No TransactionManagerLookup configured (in JTA environment, use ofread-write or transactional second-level cache is not recommended)>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Automatic flushduring beforeCompletion(): disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Automatic sessionclose at end of transaction: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <JDBC batch size:15>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <JDBC batch updatesfor versioned data: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Scrollable resultsets: enabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <JDBC3getGeneratedKeys(): disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Connection releasemode: auto>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Default batch fetchsize: 1>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Generate SQL withcomments: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Order SQL updatesby primary key: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Order SQL insertsfor batching: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Query translator:org.hibernate.hql.ast.ASTQueryTranslatorFactory>
2014-01-2612:21:47,638 INFO [org.hibernate.hql.ast.ASTQueryTranslatorFactory] - <UsingASTQueryTranslatorFactory>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Query languagesubstitutions: {}>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <JPA-QL strict compliance:disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Second-level cache:enabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Query cache:disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Cache regionfactory : org.hibernate.cache.impl.NoCachingRegionFactory>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Optimize cache forminimal puts: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Structuredsecond-level cache entries: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Echoing all SQL tostdout>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Statistics:disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Deleted entitysynthetic identifier rollback: disabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Defaultentity-mode: pojo>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Named querychecking : enabled>
2014-01-2612:21:47,638 INFO [org.hibernate.cfg.SettingsFactory] - <Check Nullabilityin Core (should be disabled when Bean Validation is on): enabled>
2014-01-2612:21:47,748 INFO [org.hibernate.impl.SessionFactoryImpl] - <buildingsession factory>
2014-01-2612:21:47,904 INFO [org.hibernate.impl.SessionFactoryObjectFactory] - <Notbinding factory to JNDI, no JNDI name configured>
2014-01-2612:21:48,013 DEBUG [org.hibernate.SQL] - <insert into myemp (ename, empno)values (?, ?)>
Hibernate: insertinto myemp (ename, empno) values (?, ?)
2014-01-2612:21:48,388 DEBUG [org.hibernate.SQL] - <select myemp0_.empno as empno0_,myemp0_.ename as ename0_ from myemp myemp0_ where myemp0_.ename=?>
Hibernate: selectmyemp0_.empno as empno0_, myemp0_.ename as ename0_ from myemp myemp0_ wheremyemp0_.ename=?
onj.edu.hibernate.model.MyEmp@1e8bec9
2014-01-2612:21:48,482 DEBUG [org.hibernate.SQL] - <select myemp0_.empno as empno0_0_,myemp0_.ename as ename0_0_ from myemp myemp0_ where myemp0_.empno=?>
Hibernate: selectmyemp0_.empno as empno0_0_, myemp0_.ename as ename0_0_ from myemp myemp0_ wheremyemp0_.empno=?
onj.edu.hibernate.model.MyEmp@1e8bec9
2014-01-2612:21:48,545 DEBUG [org.hibernate.SQL] - <update myemp set ename=? whereempno=?>
Hibernate: updatemyemp set ename=? where empno=?

댓글 없음:

댓글 쓰기