Mapping the UserDetalis Object to the Database UserDetails table
The file userdetails.hbm.xml is used to map userDetail Object to the UserDetails table in the database. Here is the code for userdetails.hbm.xml:
<hibernate-mapping>
<class name=”com.sdnext.hibernate.tutorial.dto.UserDetails” table=”UserDetails”>
<id name=”userId” type=”long” column=”ID” >
<generator class=”assigned”/>
</id>
<property name=”userName”>
<column name=”UserName” />
</property>
</class>
</hibernate-mapping>
Configuring Hibernate: here some change is required in the configuration file because we are used mapping file in stead of Annotation.
hibernate.cfg.xml:
<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>
<mapping resource=”userdetails.hbm.xml“/>
<mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>
Developing Code to Test Hibernate example:
Now there are three steps for using Hibernate API
HibernateTestDemo.java
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.sdnext.hibernate.tutorial.dto.UserDetails;
public class HibernateTestDemo {
public static void main(String[] args)
{
//Create the model object
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName(“Dinesh Rajput”);
// Create Session Factory Object – using configuration object
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//Create Session object from session factory object
Session session = sessionFactory.openSession();
session.beginTransaction();
//Use the session to save model objects
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Now you can run the application and see the result.
So in this topic we see how to use Mapping file to map the Model Object to relational database table.
In the Next Chapter We will Described the O/R Mapping file in details.
<<Previous Chapter 4<< >>Next Chapter6>>