본문 바로가기

Web/spring

[Spring Exception] Hibernate Mapping Exception – Unknown Entity

728x90

https://www.baeldung.com/hibernate-mappingexception-unknown-entity

 

 

 

Exception 시리즈 마지막 ~!


org.hibernate.MappingException: Unknown entity

 

 

 

Hibernate와 Spring 및 Hibernate 환경 모두에 대한 알 수 없는 엔티티 문제 및 해결방법이다

 

 

 

Missing or Invalid @Entity Annotation 

1. @Entity 주석이 누락된 엔티티 클래스의 경우

public class Foo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    public Foo() {
        super();
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

 

2. 잘못된 유형의 @Entity 주석

import org.hibernate.annotations.Entity;

@Entity
public class Foo implements Serializable {
    ...복사

 org.hibernate.annotations.Entity 는 더 이상 사용 되지 않는 유형의 엔티티이디ㅏ.

javax.persistence.Entity 로 바꾸어야함

import javax.persistence.Entity;

@Entity
public class Foo implements Serializable {
    ...

 

 

MappingException With Spring

LocalSessionFactoryBean  통해 어노테이션 스캐닝으로부터 SessionFactory를 부트스트래핑하는 것을 포함한다

https://www.baeldung.com/hibernate-5-spring

 

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(restDataSource());
    ...
    return sessionFactory;
}

Session Factory Bean의 이 간단한 구성에는 핵심 요소가 빠졌기 때문에 SessionFactory를 사용하려는 테스트는 실패한다

...
@Autowired
private SessionFactory sessionFactory;

@Test(expected = MappingException.class)
@Transactional
public void givenEntityIsPersisted_thenException() {
    sessionFactory.getCurrentSession().saveOrUpdate(new Foo());
}

MappingException: Unknown entity

org.hibernate.MappingException: Unknown entity: 
com.baeldung.ex.mappingexception.persistence.model.Foo
    at o.h.i.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1141)

 

두가지의 해결 방법이 있다

 

클래스 경로에서 엔터티 클래스를 검색할 패키지를 지정한다.

sessionFactory.setPackagesToScan(
  new String[] { "com.baeldung.ex.mappingexception.persistence.model" });

또는 엔티티 클래스를 세션 팩토리에 직접 등록해도 된다

sessionFactory.setAnnotatedClasses(new Class[] { Foo.class });

이러한 추가 구성 라인 중 하나를 사용하면 테스트가 올바르게 실행되고 통과된다

 

 

MappingException With Hibernate

Hibernate만 사용할 때 발생하는 오류

public class Cause4MappingExceptionIntegrationTest {

    @Test
    public void givenEntityIsPersisted_thenException() throws IOException {
        SessionFactory sessionFactory = configureSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.saveOrUpdate(new Foo());
        session.getTransaction().commit();
    }

    private SessionFactory configureSessionFactory() throws IOException {
        Configuration configuration = new Configuration();
        InputStream inputStream = this.getClass().getClassLoader().
          getResourceAsStream("hibernate-mysql.properties");
        Properties hibernateProperties = new Properties();
        hibernateProperties.load(inputStream);
        configuration.setProperties(hibernateProperties);

        // configuration.addAnnotatedClass(Foo.class);

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
          applySettings(configuration.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }
}

 

 

 

hibernate-mysql.properties 파일에는 Hibernate 구성 속성이 포함되어 있다.

hibernate.connection.username=tutorialuser
hibernate.connection.password=tutorialmy5ql
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.url=jdbc:mysql://localhost:3306/spring_hibernate5_exceptions
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create

 

 

이 테스트를 실행하면 동일한 매핑 예외가 발생한다.

org.hibernate.MappingException: 
  Unknown entity: com.baeldung.ex.mappingexception.persistence.model.Foo
    at o.h.i.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1141)

구성에서 빠진 것은 엔터티 클래스의 메타데이터( Foo )를 구성에 추가하면 된다

configuration.addAnnotatedClass(Foo.class);

이렇게 하면 테스트가 수정되어 이제 Foo 엔터티를 유지할 수 있다.

728x90