We’ll look at one of the several ways we can fetch data from the database using Hibernate: the session.get method.

Now look following example…

UserDetails.java

package com.sdnext.hibernate.tutorial.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name=”USER_TABLE”)
public class UserDetails
{
@Id
@Column(name=”USER_ID”)
private int    userId;

@Column(name=”USER_NAME”)
private String userName;

public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString()
{
return “[User Name: “+userName+”User Id: “+userId+”]”;
}
}

This is user domain persistence class UserDetails to store data into table USER_TABLE with columns name USER_ID and USER_NAME corresponding persisting field userId and userName respectively.

Now we have to configure hibernate configuration file.

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>
<!– 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”>root</property>
<property name=”connection.password”>root</property>

<!– JDBC connection pool (use the built-in) –>
<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>

<!– Echo all executed SQL to stdout –>
<property name=”show_sql”>true</property>

<!– Drop and re-create the database schema on startup –>
<property name=”hbm2ddl.auto”>update</property>

<mapping class=”com.sdnext.hibernate.tutorial.dto.UserDetails”/>

</session-factory>
</hibernate-configuration>

here we are using MySql database hibernateDB. Now we running the code with following class file
HibernateTestDemo.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;

public class HibernateTestDemo {
/**
* @param args
*/
public static void main(String[] args)
{
UserDetails user = new UserDetails(); //Creating first user
user.setUserId(1);
user.setUserName(“Dinesh Rajput”);

UserDetails user2 = new UserDetails();//Creating second user
user2.setUserId(2);
user2.setUserName(“Anamika Rajput”);

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //Creating a session factory object
Session session = sessionFactory.openSession(); //Creating a session object for inserting users  object to the database table USER_TABLE
session.beginTransaction(); //Open the transaction of session object to do something

session.save(user); //Inserting or Saving the first user object        session.save(user2);  //Inserting or Saving the second user object

session.getTransaction().commit();//Close the transaction of session object after to do something
session.close(); //Close the session object performing saving event to database

user = null;  //Now getting a user object from database table from session object
session = sessionFactory.openSession(); //Creating a new session object for fetching user object
session.beginTransaction(); //Again Open the transaction of the session object

user = (UserDetails) session.get(UserDetails.class, 1); //we get user object from session object using method session.get(Class arg1, Serializable arg2) here arg2 is primary key or id of the fetching object and arg1 is the what the model object we want to retrieve from database.

System.out.println(user);
}
}

Here after running this code we get following output…

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_TABLE (USER_NAME, USER_ID) values (?, ?)
Hibernate: insert into USER_TABLE (USER_NAME, USER_ID) values (?, ?)
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.USER_NAME as USER2_0_0_ from USER_TABLE userdetail0_ where userdetail0_.USER_ID=?
[User Name: Dinesh Rajput User Id: 1]
Retrieving Objects in Hibernate using session.get

In the Next Chapter we will see that how to work update query in hibernate.

<<Previous Chapter 9<<    >>Next Chapter11>>