Select Query Hibernate example

Select Query Hibernate example

Many ways are available to get data from the table if you are using Hibernate. Here you will see three different ways to get data from the table. Eventually all technique will give you same result as Hibernate allows all old approach. Recommendation would be if you are using Hibernate use ORM java object to get data form the table.

  • Sample create table script:
create table OTC.dbo.Test (
	test_id int identity not null,
	smID varchar (20) null,
	eventDate date null,
	createTime datetime default getdate() null,
	updateTime datetime null,
	primary key (test_id) 
)

For test insert some data into the table script:

INSERT INTO OTC.dbo.Test(
   smID
  ,eventDate
  ,updateTime
) VALUES (
   '987456'  -- smID - IN varchar(20)
   ,'20151226' -- eventDate - IN date
   ,'12/26/2015 12:00:00 AM' -- updateTime - IN datetime
)
  • TestModel class:
import java.util.Date;

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

@Entity
@Table(name = "OTC.dbo.Test")
public class TestModel {
	
	@Id
	@Column(name="test_id")
	private String test_id;
	
	@Column(name="smID")
	private String smID;
	
	@Column(name="eventDate")
	private java.sql.Date eventDate;
	
	@Column(name="createTime")
	private Date createTime;
	
	@Column(name="updateTime")
	@Temporal(TemporalType.TIMESTAMP)
	private Date updateTime;
	
	//Getters and Setters method...

}
  • By using HQL query:
@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
public List<T> getDataByHQLQuery() {
	
	Session session = sessionFactory.getCurrentSession();
	Query query = session.createQuery("from TestModel");				
	
	List<T> dataList = query.list();
	return dataList;
}
  • By using Criteria interface API:
@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
public List<T> getDataByUsingCriteria() {
	
	Session session = sessionFactory.getCurrentSession();
	List<T> datalist = session.createCriteria(TestModel.class).list();
	return datalist;			
}
  • By using pure native SQL select statement (Not recommended)
@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
public List<T> getDataByNativeSelectQuery() {
	
	Session session = sessionFactory.getCurrentSession();
	Query query = session.createSQLQuery("select * from OTC.dbo.Test");				
	
	List<T> dataList = query.list();
	return dataList;
}

download Download Project: HibernateSelectQueryExample

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *