1

I'm working on a Java project using Hibernate for database interactions. I have multiple entity classes annotated with @Entity and mapped to corresponding database tables. In my hibernate.cfg.xml configuration file, I'm using the <mapping class="com.example.model.User"/> tag to specify each entity class.

My question is whether I need to include this entry for every entity class in the project or if there's a more efficient way to configure Hibernate to automatically detect and map all annotated entity classes without explicitly listing them in the hibernate.cfg.xml file.

Could someone clarify the recommended approach and whether it's necessary to repeatedly list each entity class in the hibernate.cfg.xml file? If there's a more streamlined way to handle this, I'd appreciate any guidance or examples. Thanks!

I've seen some examples where only the base package name is specified, and Hibernate scans and maps all entity classes within that package. However, I'm unsure about the best approach and whether this can lead to potential issues in larger projects.

My hibernate.cfg.xml file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.community.dialect.SQLiteDialect</property>
        <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
        <property name="hibernate.connection.url">jdbc:sqlite:fuelvalley.sqlite</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.use_sql_comments">true</property>
        <mapping class="com.example.erp.models.Users"/>
    </session-factory>
</hibernate-configuration>
Sergey Tsypanov
  • 3,265
  • 3
  • 8
  • 34
asif
  • 11
  • 4

1 Answers1

0

Which version of Hibernate do you use? In modern versions (5+) you don't need to enlist entities anywhere, especially when using Spring Data JPA.

Alternatively, you can specify package to scan for Hibernate's Sessionfactory. See e.g. https://stackoverflow.com/a/11257714/12473843 or https://stackoverflow.com/a/16088340/12473843

Sergey Tsypanov
  • 3,265
  • 3
  • 8
  • 34