Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. The Problem

This article is going to discuss the org.hibernate.MappingException: Unknown entity issue and solutions, both for Hibernate as well as for a Spring and Hibernate environment.

Further reading:

Bootstrapping Hibernate with Spring

A quick and practical guide to integrating Hibernate 5 with Spring.

@Immutable in Hibernate

A quick and practical guide to @Immutable annotation in Hibernate

HibernateException: No Hibernate Session Bound to Thread in Hibernate 3

Discover when "No Hibernate Session Bound to Thread" exception gets thrown and how to deal with it.

2. Missing or Invalid @Entity Annotation

The most common cause for the mapping exception is simply an entity class missing the @Entity annotation:

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;
    }
}

Another possibility is that it may have the wrong type of @Entity annotation:

import org.hibernate.annotations.Entity;

@Entity
public class Foo implements Serializable {
    ...

The deprecated org.hibernate.annotations.Entity is the wrong type of entity to use – what we need is the jakarta.persistence.Entity:

import jakarta.persistence.Entity;

@Entity
public class Foo implements Serializable {
    ...

3. MappingException With Spring

The configuration of Hibernate in Spring involves bootstrapping the SessionFactory from annotation scanning, via a LocalSessionFactoryBean:

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

This simple configuration of the Session Factory Bean is missing a key ingredient, and a test trying to use the SessionFactory will fail:

...
@Autowired
private SessionFactory sessionFactory;

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

The exception is, as expected – the MappingException: Unknown entity:

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

Now, there are two solutions to this problem – two ways ways to tell the LocalSessionFactoryBean about the Foo entity class.

We can specify which packages to search for entity classes in the classpath:

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

Or we can simply register the entity classes directly into the Session Factory:

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

With either of these additional configuration lines, the test will now run correctly and pass.

4. MappingException With Hibernate

Let’s now see the error when using just 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;
    }
}

The hibernate-mysql.properties file contains the Hibernate configuration properties:

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

Running this test will result in the same mapping exception:

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

As it is probably already clear from the example above, what is missing from the configuration is adding the metadata of the entity class – Foo – to the configuration:

configuration.addAnnotatedClass(Foo.class);

This fixes the test – which is now able to persist the Foo entity.

5. Conclusion

This article illustrated why the Unknown entity Mapping Exception may occur, and how to fix the problem when it does, first at the entity level, then with Spring and Hibernate and finally, just with Hibernate alone.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW