Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
<hibernate-configuration>
<session-factory>
<!– Database connection settings –>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost:3306/hibernateDB</property>
<property name=”connection.username”>username</property>
<property name=”connection.password”>password</property>
<property name=”connection.pool_size”>1</property>
<!– SQL dialect –>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<!– Enable Hibernate’s automatic session context management –>
<property name=”current_session_context_class”>thread</property>
<!– Disable the second-level cache –>
<property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>
<!– Show all executed SQL to stdout –>
<property name=”show_sql”>true</property>
<!– Drop and re-create the database schema on startup –>
<property name=”hbm2ddl.auto”>create</property>
<!– Mapping files –>
<mapping resource=”userdetails.hbm.xml”/>
</session-factory>
</hibernate-configuration>
Here <property name=”hbm2ddl.auto”>create</property> means schema DDL created every time when SessionFactory Object is created.
UserDetails.java
Now we run this example–
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Now we get following table structure–
Again we running the following example-
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Now we get the following table schema–
Here we see that the previous data is destroyed when we are using in the hibernate.cfg.xml file using the following line.
<property name=”hbm2ddl.auto”>create</property>
Here
hbm2ddl.auto–>create -Always create new schema
hbm2ddl.auto–>update -Update existing schema
Now we are replacing above line with the <property name=”hbm2ddl.auto”>update</property>
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Hibernate: insert into USER_DETAILS ( USER_ID, USER_NAME) values (?, ?)
Now we get the following table schema…
here we are looking the table USER_DETAILS only updated not again created.
Now in the Next Chapter we will learn about how to retrieve an object from database.
<<Previous Chapter 8<< >>Next Chapter10>>