Hibernate configuration file (.cfg.xml) fo

2019-02-22 05:59发布

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>

2条回答
劫难
2楼-- · 2019-02-22 06:41

WE can't configure the multiple databases in single configuration file.if we use multiple databases we have to use multiple configuration file. in respective tables we can configure in respective configuration file.

查看更多
爷的心禁止访问
3楼-- · 2019-02-22 06:52

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.

查看更多
登录 后发表回答