I am experimenting with Hibernate for my Java web app. The following is part of my hibernate.cfg.xml, and I wondering how to map multiple database tables in the same configuration file. I use annotations to map my models to mysql database table, and I have multiple model classes (for example: models.Book), how to map the models in hibernate.cfg.xml?
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test_db</property>
<property name="connection.username">root</property>
<property name="connection.password">xxx</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>
<mapping class ="models.Category" />
</session-factory>
</hibernate-configuration>
Yes, you can.
Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate. properties, or as an XML file named hibernate. cfg.
The config file hibernate. cfg. xml needs to be on the classpath . This can be accomplished in different ways, depending on your project.
We should not specify mappings in cfg.xml file. It has to be done by either annotations or XML. For Annotations: The cfg.xml file that is provided by you looks ok, if we are using the annotations to indicate database mappings with entity classes.
To use XML way of mapping between Entities and Tables, an hbm.xml file needs to be created and in that case, Replace
<mapping class ="models.Category" />
with something like
<mapping resource="models/Book.hbm.xml></mapping>
and hbm.xml file contains the necessary mapping as follows. for example:
<hibernate-mapping>
<class name="models.Book" table="Book" catalog="your database name">
<id name="bookId" type="java.lang.Integer">
<column name="BOOKID" />
<generator class="identity" />
</id>
<property name="authorName" type="string">
<column name="AUTHOR_NAME" length="10" not-null="true" unique="true" />
</property>
</class>//all the database mappings
</hibernate-mapping>
Sorry, if I understand your question wrongly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With