AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



hibernate-basics: How to create tables automatically in hibernate?

Please give me sample code to write mapping file and hibernate configuration file to create the tables automatically in oracle or any other database.

hibernate x 23
basics x 171
Posted On : 2014-05-14 17:41:25.0
profile Rishi Kumar - anyforum.in Rishi Kumar
523188245674
up-rate
5
down-rate

Answers


In mapping file we just put the information of table structure for a persistent class. Suppose we have a persistent class named Employee then mapping file should be like following:

employee.hbm.xml:
----------------------------

<?xml version=´1.0´ encoding=´UTF-8´?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="firstName"></property>
<property name="lastName"></property>

</class>

</hibernate-mapping>


When we switch the database we mainly need to make changes in hibernate.cfg.xml file. In this case mapping file only needs some changes sometimes when we use generator class other than assigned and native.



Following is the configuration file which needs all changes while switching the database. In configuration file we mention all the mapping files also like below:
<mapping resource="employee.hbm.xml"/>

Now the configuration file will look like this:

hibernate.cfg.xml:
---------------------------
<?xml version=´1.0´ encoding=´UTF-8´?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Following property is used to create the tables automatically -->
<property name="hbm2ddl.auto">update</property>

<!-- Following properties are Database dependent -->
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>


<!-- Mapping files entries -->
<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

Posted On : 2014-05-14 18:11:06
Satisfied : 1 Yes  10 No
profile Saksham Kumar - anyforum.in Saksham Kumar
73433936114
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in