There
are many ways to retrieve data from databases using Hibernate. I am going to
explain simple way now. Session class has “get” method, you just need to pass
entity/class name and primary key of this entity as parameters to this method.
It gives you the object corresponds to this primary key.
Object get(Class
class,Serializable id)
Return
the persistent instance of the given entity class with the given identifier, or
null if there is no such persistent instance.
package myFirstHibernate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.Date; @Entity public class Employee { @Id @Column(name="emp_id") private int id; private String firstName; private String lastName; private String designation; private int age; private double salary; @Lob private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/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/sample</property> <property name="connection.username">root</property> <property name="connection.password">tiger</property> <!-- Enable the logging of all the generated SQL statements to the console --> <property name="show_sql">true</property> <!-- Format the generated SQL statement to make it more readable, --> <property name="format_sql">false</property> <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do --> <property name="use_sql_comments">false</property> <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <!-- mappings for annotated classes --> <mapping class="myFirstHibernate.Employee" /> </session-factory> </hibernate-configuration>
package myFirstHibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import java.util.Date; public class TestEmployee { /* Step 1: Create session factory */ private static SessionFactory getSessionFactory() { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(). applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder.build()); return factory; } public static void main(String args[]){ Employee emp1 = new Employee(); emp1.setAge(26); emp1.setDesignation("Senior Software Developer"); emp1.setFirstName("Hari Krishna"); emp1.setId(1); emp1.setLastName("Gurram"); emp1.setSalary(80000); emp1.setDescription("Whaterver the world i saw yesterday is absolutely different from today"); /* To persisit data */ SessionFactory sessionFactory = getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(emp1); session.getTransaction().commit(); session.close(); /* To retrieve data */ Session session1 = sessionFactory.openSession(); session1.beginTransaction(); Employee emp = (Employee)session1.get(Employee.class, 1); session1.getTransaction().commit(); session1.close(); System.out.println(emp1.getId() + " " + emp1.getFirstName() + " " + emp1.getLastName()); } }
Run
TestEmployee class, you will get output like below.
Hibernate: drop table if exists Employee Hibernate: create table Employee (emp_id integer not null, age integer not null, description longtext, designation varchar(255), firstName varchar(255), lastName varchar(255), salary double precision not null, primary key (emp_id)) Dec 20, 2014 8:00:27 AM org.hibernate.tool.hbm2ddl.SchemaExport execute INFO: HHH000230: Schema export complete Hibernate: insert into Employee (age, description, designation, firstName, lastName, salary, emp_id) values (?, ?, ?, ?, ?, ?, ?) Hibernate: select employee0_.emp_id as emp_id1_0_0_, employee0_.age as age2_0_0_, employee0_.description as descript3_0_0_, employee0_.designation as designat4_0_0_, employee0_.firstName as firstNam5_0_0_, employee0_.lastName as lastName6_0_0_, employee0_.salary as salary7_0_0_ from Employee employee0_ where employee0_.emp_id=? 1 Hari Krishna Gurram
/*
To retrieve data */
Session
session1 = sessionFactory.openSession();
session1.beginTransaction();
Employee
emp = (Employee)session1.get(Employee.class, 1);
session1.getTransaction().commit();
session1.close();
As
you observe above snippet, I created another session, begins transaction, calls
get method of session to retrieve object from database and commit the
transaction. It is very simple……….
No comments:
Post a Comment