2011-02-08 3 views
10

봄 3 mvc로 최대 절전 모드를 사용하려고하는데,이 순간 예외가 발생합니다. 나는 나의 hibernate.cfg.xml을 어딘가에 정의 할 필요가 있다고 생각하지만, 확실하지 않다.org.hibernate.HibernateException : /hibernate.cfg.xml을 찾을 수 없습니다.

는 기본적으로 내가 여기 http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/이 예제를 따라 그리고 특히이 "마술"을 사용하여 내 hibernate.cfg 파일을 찾을 생각이 코드 줄 보았다 : 나는 추측하고있어

return new Configuration().configure().buildSessionFactory(); 

을 그가 정확하지를 ? 아래

src/com/jr/hibernate/ 내 CFG 파일입니다 내부 나는 현재 나의 hibernate.cfg 파일이 :

<?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://localhost:3306/racingleague</property> 
    <property name="connection.username">username</property> 
    <property name="connection.password">password</property> 
    <property name="hibernate.format_sql">true</property> 
    <!-- JDBC connection pool (use the built-in) --> 
    <property name="connection.pool_size">1</property> 
    <!-- SQL dialect --> 
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
    <!-- Enable Hibernate's automatic session context management --> 
    <property name="current_session_context_class">thread</property> 
    <!-- Disable the second-level cache --> 
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
    <!-- Echo all executed SQL to stdout --> 
    <property name="hibernate.show_sql">true</property> 
    <!-- Drop and re-create the database schema on startup --> 
    <property name="hibernate.hbm2ddl.auto">update</property> 
    <!--property name="hbm2ddl.auto">update</property--> 
    <mapping resource="com/jr/model/hibernateMappings/user.hbm.xml"/> 
    </session-factory> 
</hibernate-configuration> 

내 최대 절전 모드 유틸 클래스 :

:이 추상 클래스 BU 호출되는

package com.jr.utils; 

import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 

public class HibernateUtils { 

    private static final SessionFactory sessionFactory = buildSessionFactory(); 

     public static SessionFactory buildSessionFactory() { 
     try { 
      // Create the SessionFactory from hibernate.cfg.xml 
      return new Configuration().configure().buildSessionFactory(); 
     } 
     catch (Throwable ex) { 
      // Make sure you log the exception, as it might be swallowed 
      System.err.println("Initial SessionFactory creation failed." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
     } 

} 

package com.jr.db; 

import org.hibernate.SessionFactory; 
import org.hibernate.classic.Session; 

import com.jr.utils.HibernateUtils; 

public abstract class DbWrapper<T> { 

    private static SessionFactory sessionFactory = null; 
    private static Session session; 

    public DbWrapper() { 
     setSessionFactory(); 
    } 

    private void setSessionFactory() { 
     sessionFactory = HibernateUtils.buildSessionFactory(); 
     session = sessionFactory.getCurrentSession(); 
    } 

    public boolean addNewItem(T dbItem) { 

     try { 
      session.getTransaction().begin(); 
      session.save(dbItem); 
      session.getTransaction().commit(); 
     } catch (Exception e) { 
      System.err.println("error exception when adding new item to table" 
        + e); 
     } finally { 

      session.close(); 
      sessionFactory.close(); 
     } 

     return false; 

    } 

    public abstract boolean removeItem(String uid); 

    public abstract boolean modifyItem(String uid, T item); 

} 

그리고 여기에 원래 몇 가지 최대 절전 모드를 실행하는 컨트롤러가 있습니다 물건 :

private Logger logger = Logger.getLogger(UserController.class); 

    private UserDb userDb; 

@RequestMapping(value = "/user/registerSuccess", method = RequestMethod.POST) 
public String submitRegisterForm(@Valid User user, BindingResult result) { 

    // validate the data recieved from user 
    logger.info("validate the data recieved from user"); 
    if (result.hasErrors()) { 
     logger.info("form has "+result.getErrorCount()+" errors"); 

     return "account/createForm"; 
    } else{ 
     // if everthings ok, add user details to database 
     logger.info("if everthings ok, add user details to database"); 

     userDb = new UserDb(); 

     userDb.addNewItem(user); 

     // display success and auto log the user to the system. 
     return "account/main"; 
    } 

} 

환호 내 hibernate.cfg.xml 파일과 동일한 위치에 모든 테이블 hibvernate xml 매핑이 있습니다.

답변

25

hibernate.cfg.xml 파일을 src/com/jr/hibernate/ 디렉토리에 두는 대신 src 디렉토리에 두십시오. 그런 다음 여기에 언급 된대로 WEB-INF/classes 디렉토리에 자동으로 나타납니다.

+0

건배. 그것은 작동합니다. 나는 또 다른 질문이있다. 내 응용 프로그램은 내 최대 절전 모드 xml 매핑을 찾을 수 없습니다. 나는 그것을 com.jr.hibernateMappings에 넣었지만 build.xml은 hbm.xml 파일을 빌드하고 컴파일하는 것처럼 보이지 않는다. 다시 잘못된 위치에 있습니까? WAR/WEB-INF/classes 폴더에 있어야합니까? 가능하다면 src 디렉토리 안에있는 것이 더 좋을 것입니다. – jonney

+0

고마워요. 내 파일 (hibernate.cfg.xml)을 src로 옮긴 후, 덕분에 파일을 찾을 것입니다. –

13

hibernate.cfg.xml은 webapp가 시작될 때 classpath의 루트에 있어야합니다.

maven을 사용하여 프로젝트를 빌드하는 경우 hibernate.cfg.xml을 src/main/resources 디렉토리에 넣으십시오. 그러면 war 패키지를 빌드 할 때 자동으로 /WEB-INF/classes에 배치됩니다.

maven을 사용하지 않는 경우 파일을 WEB-INF/classes 디렉토리에 직접 배치하십시오.

4

hibernate.cfg.xmlWEB-INF/classes이어야합니다. 또는 해당 인수를 configure(..) 메서드에 전달하여 사용자 지정 위치에서로드 할 수도 있습니다.

+0

Bozho,'config.configure ("/ resources/hibernate.cfg.xml");'나를 위해 작동하지 않습니다. 사실, 나는 간단한 "최대 절전 모드 3.1"응용 프로그램을하고있다. Btw,'config'는'AnnotationConfiguration' 타입입니다. –

0

IntelliJ에서 "프로젝트 설정 열기">> 모듈 >> 프로젝트에 사용 된 hibernate.cfg.xml 파일을 최대 절전 모드로 전환하고 대상을 지정하십시오.

0

나는 동일한 문제가 있으며 해결 된 hibernate.cfg.xml을 src/main/resources 디렉토리로 옮겼다. 자동으로/WEB-INF/classes에 위치 할 것이다.

2

Maven을 사용하는 경우 Intellij IDEA의 /src/main/java/resources/hibernate.cfg.xml 경로에 hibernate.cfg.xml 파일을 저장해야합니다. . 그런 다음 실행 응용 프로그램 클래스에 단지 라인을 삽입합니다. = 새 구성() 구성 ("있는 hibernate.cfg.xml")

SessionFactory에 공장을 addAnnotatedClass을().buildSessionFactory();

+0

Thnx. 나는 이틀 후 거의 낭비했다. – SAM