• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Hibernate

query by example in hibernate

April 6, 2017 By j2eereference Leave a Comment

query by example in hibernate

If you have multiple criteria to be set for fetching data from database , Hibernate provide a feature called query by example. Here you can create an example object with all the properties set to it . This object can be passed to   Example.create() method.  Lets try to understand querybyExample with the below example code.

Here in this example lets pull the record from Employee table with column value for emp_name as “Alex” .

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.j2eereference.hibernate.queryByExample;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "employee")
public class Employee {
private int emp_id;
private String emp_name;
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
 
}

QueryByExampleDemo .java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.j2eereference.hibernate.queryByExample;
 
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Example;
 
public class QueryByExampleDemo {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee empExample=new Employee();
empExample.setEmp_name("Alex");
Example example= Example.create(empExample);
Criteria crtiteria=session.createCriteria(Employee.class).add(example);
List empList=crtiteria.list();
for(Employee employee:empList){
System.out.println("Emp Name is  "+employee.getEmp_name());
}
}
}

output:

Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_ from employee this_ where (this_.emp_name=?)
Emp Name is Alex.

Query by Example : excludeProperty

It is possible to exclude properties also as below. We can have as many exclude property as we need.

1
Example example= Example.create(empExample).excludeProperty("emp_age");

Query by Example :enableLike

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.j2eereference.hibernate.queryByExample;
 
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Example;
 
public class QueryByExampleDemo {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee empExample=new Employee();
empExample.setEmp_name("A%");
Example example= Example.create(empExample).enableLike();
Criteria crtiteria=session.createCriteria(Employee.class).add(example);
List empList=crtiteria.list();
for(Employee employee:empList){
System.out.println("Emp Name is  "+employee.getEmp_name());
}
}
}

output:

Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_ from employee this_ where (this_.emp_name like ?)
Emp Name is Alex

Conclusion:

Query by Example is useful if you have lot of properties to set for  your query.

Query by Example  is not applicable for Primary key column, So if you give primary key column for QueryByExample it is going to return all the records.

Query by Example  is not applicable for column with null value.

Related Posts

  • First level caching in Hibernate
  • Hibernate – Query By Criteria
  • Hibernate Query Language
  • Many to Many mapping in hibernate
  • One To Many mapping using Hibernate
  • one to one mapping using Hibernate
  • Implementing composite primary key with JPA and Hibernate
  • How to implement primary key with JPA and Hibernate
  • What is Hibernate?

Filed Under: Hibernate

How to call stored procedure in Hibernate

June 11, 2015 By j2eereference Leave a Comment

How to call stored procedure in Hibernate

There are different ways to call stored procedure from hibernate using

  • NamedNativeQuery
  • NamedQuery
  • sql-query in XML file

In this article we are going to see how to call a stored procedure from hibernate using NamedNativeQuery .

Consider we have a stored procedure GetEmployee created in MySQL , which accepts one input parameter and return the row.

1
2
3
4
5
6
delimiter //
 
CREATE PROCEDURE GetEmployee(emId VARCHAR(20))
BEGIN
SELECT * FROM employee WHERE emp_id = emId;
END//

Now lets see how to call this Stored procedure, using NamedNativeQuery.

 Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.j2eereference.hibernate.storedProcedure;
 
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
import org.hibernate.annotations.NamedNativeQueries;
import org.hibernate.annotations.NamedNativeQuery;
 
@NamedNativeQueries({
@NamedNativeQuery(
name = "callEmployeeSP",
query = "call GetEmployee(:empID)",
resultClass = Employee.class
)
})
 
@Entity
@Table(name = "employee")
public class Employee {
 
private int emp_id;
private String emp_name;
 
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}

Using the below class , we can call the stored procedure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.j2eereference.hibernate.storedProcedure;
 
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class SPCallDemo{
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
        Query query = session.getNamedQuery("callEmployeeSP");
query.setString("empID", "1");  
        List employees=query.list();
        System.out.println("Employee Name is  : "+employees.get(0).getEmp_name());
session.close();
}
}

Output:
Hibernate: CALL GetEmployee(?)

Employee Name is  : John

 

 

Filed Under: Hibernate

get and load in Hibernate

June 6, 2015 By j2eereference Leave a Comment

get and load in Hibernate

Hibernate session provides two methods – get and load to access the objects. Both are doing same kind of functionality , But there are some differences.

Lets try to understand those differences with example .

1)  get method hit the DB immediately . But Load wont hit the DB immediately until we invoke the object

load() method : This returns a proxy object by default and there won’t be any database hit until we invoke it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.j2eereference.hibernate;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class TestGetLoad {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee emp=(Employee)session.load(Employee.class, 1);
System.out.println("Before invoking the object");
System.out.println("Employee name is  "+emp.getEmp_name());
session.close();
}
}

 Output:

1
2
3
Before invoking the object
Hibernate: select employee0_.emp_id as emp1_0_0_, employee0_.emp_name as emp2_0_0_ from employee employee0_ where employee0_.emp_id=?
Employee name is  Jose

Here you can notice the DB hit happened only after we invoked the object with  emp.getEmp_name().

get() method .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.j2eereference.hibernate;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class TestGetLoad {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee emp=(Employee)session.get(Employee.class, 1);
System.out.println("Before invoking the object");
System.out.println("Employee name is  "+emp.getEmp_name());
session.close();
}
}

output:

1
2
3
Hibernate: select employee0_.emp_id as emp1_0_0_, employee0_.emp_name as emp2_0_0_ from employee employee0_ where employee0_.emp_id=?
Before invoking the object
Employee name is  Rakesh

Here you can notice that the DB hit happened immediately.

2)  load () method will throw exception  if there is no record in the DB with given unique ID , But get will return null .

We have an employee table and it has only one record , emp_id is 1 . Now lets try fetching the object with unique emp_id 10 which is not available.

load() method: This method will throw exception when we try to load employee object with unique id 10 , which does not exist

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.j2eereference.hibernate;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class TestGetLoad {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee emp=(Employee)session.load(Employee.class, 10);
System.out.println("emp is  "+emp);
session.close();
}
}

output:

1
2
3
4
5
6
7
8
9
10
11
Hibernate: select employee0_.emp_id as emp1_0_0_, employee0_.emp_name as emp2_0_0_ from employee employee0_ where employee0_.emp_id=?
<span style="color: red;">Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.j2eereference.hibernate.Employee#10]
at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:377)
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:79)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:68)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
at com.j2eereference.hibernate.getLoad.Employee$$EnhancerByCGLIB$$63203938.toString()
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at com.j2eereference.hibernate.getLoad.TestGetLoad.main(TestGetLoad.java:14) </span>

get() method: This method will return null when we try to get employee object with unique id 10 , which does not exist

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.j2eereference.hibernate.getLoad;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class TestGetLoad {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee emp=(Employee)session.get(Employee.class, 10);
System.out.println("emp is  "+emp);
session.close();
}
}

output

1
2
Hibernate: select employee0_.emp_id as emp1_0_0_, employee0_.emp_name as emp2_0_0_ from employee employee0_ where employee0_.emp_id=?
emp is  null

Conclusion :

  • If you are not sure that the object exists , use get method.
  •  If you are sure that the object exist, you can use load method to access the objet.
  • get method will return a completely initialized object which may involve multiple DB hits based upon object relational mapping.
  • load() method returns a proxy which can be initialized on demand.

Filed Under: Hibernate

projection in hibernate

June 1, 2015 By j2eereference Leave a Comment

Projection in hibernate

In this article we are going to see one of the important criteria API feature called Projection. There are lot of things you can do with Projection . Here let’s see some of the important usages of projection.

Projection for Aggregation:

Projection can be used to perform aggregations like count,max etc.,  The below example shows how to use projection for getting the count of employees.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.j2eereference.hibernate.projection;
 
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Projections;
 
import com.j2eereference.hibernate.namedQuery.Employee;
 
public class ProjectionDemo {
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
 
Criteria criteria=session.createCriteria(Employee.class)
.setProjection(Projections.count("emp_name"));
List empCountList=criteria.list();
if (empCountList != null && empCountList.size() > 0) {
                      System.out.println("Count is" +empCountList.get(0));
                   }
session.close();
}
}

Projection to fetch a particular Property.

We can get a particular column values by adding projection to a criteria. The below example shows how to get only emp_name field from Employee table using Projection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.j2eereference.hibernate.projection;
 
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Projections;
 
import com.j2eereference.hibernate.namedQuery.Employee;
 
public class ProjectionDemo {
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
 
Criteria criteria=session.createCriteria(Employee.class)
.setProjection(Projections.property("emp_name"));
 
List empNameList=(List)criteria.list();
for(String empName:empNameList){
System.out.println(empName);
}
session.close();
}
}

Hibernate Criteria With Multiple Projections:

We can add any number of projects to a criteria, In the below example we are going to fetch two columns emp_name and emp_id.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.j2eereference.hibernate.projection;
 
import java.util.Iterator;
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
 
import com.j2eereference.hibernate.namedQuery.Employee;
 
public class ProjectionDemo {
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
ProjectionList plist=Projections.projectionList();
plist.add(Projections.property("emp_name"));
plist.add(Projections.property("emp_id"));
        
                Criteria criteria=session.createCriteria(Employee.class).setProjection(plist);
             List<Object[]> list=criteria.list();
Iterator itr=list.iterator();
while(itr.hasNext())
{
Object ob[] = (Object[])itr.next();
System.out.println(ob[0]+" - "+ob[1]);
}
session.close();
}
}

Filed Under: Hibernate

Hibernate NamedNative Query

May 28, 2015 By j2eereference Leave a Comment

Hibernate NamedNative Query

Hibernate framework provides the concept of named native queries to put your native SQL into the XML mapping file or via annotation.

Advantage of using NamedNative Query

Developers like to put SQL string literals scatter all over the Java code. Hence it is very hard to maintain the code and also the code looks ugly. This can be avoid using named native query concept.

How to use NamedNative Query

The hibernate namedNative query is a way to use any query with meaningful name.

There are two ways to define the named native query :
•by annotation
•by mapping file.

Hibernate NamedNtive Query by annotation example:

Let’s see the example of using the named native queries with annotation:

We have the below files to understand using named native query:

• Employee.java
• hibernate.cfg.xml
• NamedNativeQueryDemo

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.j2eereference.hibernate.namedQuery;
 
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
 
@NamedNativeQueries({
@NamedNativeQuery(
name = "findEmployeeByName",
query = "select * from employee e where e.emp_name= :name",
        resultClass = Employee.class
)
})
 
@Entity
@Table(name = "employee")
public class Employee {
private int emp_id;
private String emp_name;
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}

Here we are using annotations to defined the named native query inside the persistent class. Here you can notice we have used two annotations

@NamedNativeQueries: This annotation is used to define the multiple named native queries.

@NamedNativeQuery : This annotation is used to define the single named native query.

You have to declare the ‘resultClass’ to let Hibernate know what is the return type, If you fail to add this , You will get an exception “org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported“.

hibernate.cfg.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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/j2eereference</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>      
    </session-factory>
</hibernate-configuration>

NamedNativeQueryDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.j2eereference.hibernate.namedQuery;
 
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class NamedNativeQueryDemo{
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.getNamedQuery("findEmployeeByName");  
query.setString("name", "Bob");
        System.out.println("Named native query is :"+query.getQueryString());    
        List employees=query.list();
session.close();
}
}

Output:

Named native query is : select * from employee e where e.emp_name= :name

 

Filed Under: Hibernate

Hibernate Named Query

May 27, 2015 By j2eereference Leave a Comment

Hibernate Named Query

Hibernate framework provides the concept of named queries to put your HQL into the XML mapping file or via annotation.

Why Named Query?

Developers like to put HQL string literals scatter all over the Java code. Hence it is very hard to maintain the code and also the code looks ugly. This can be avoided using named query concept.

How to use Named Query

The hibernate named query is a way to use any query with some meaningful name.

There are two ways to define the named query in hibernate:
•Using annotation
•Using mapping file.

Hibernate Named Query by annotation example

Let’s see the example of using the named queries with annotation

In this example, we are using annotations to defined the named query in the persistent class.  We have the below files to understand using namedquery:

• Employee.java
• hibernate.cfg.xml
• NamedQueryDemo

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.j2eereference.hibernate.namedQuery;
 
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
 
@NamedQueries({  
      @NamedQuery(  
        name = "findEmployeeByName",  
        query = "from Employee e where e.emp_name = :name"  
       )  
    })
@Entity
@Table(name = "employee")
public class Employee {
private int emp_id;
private String emp_name;
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}

In the above class we have used two annotations:

@NameQueries  :  This annotation is used to define the multiple named queries.

@NameQuery      :  This annotation is used to define the single named query.

hibernate.cfg.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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/j2eereference</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        
    </session-factory>
</hibernate-configuration>

NamedQueryDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.j2eereference.hibernate.namedQuery;
 
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class NamedQueryDemo{
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.getNamedQuery("findEmployeeByName");  
query.setString("name", "Bob");
        System.out.println("Named query is : "+query.getQueryString());    
        List employees=query.list();
session.close();
}
}

Output:
Named query is  : from Employee e where e.emp_name = :name

Advantages of using named query:

  • Compiled and validated at the time of application startup.
  • Easier to maintain than string literals embedded in the code.
  • We can avoid duplicate code.

Disadvantage of using Named query:

  • Native queries cannot be customized at run time.

 

Filed Under: Hibernate

Setting up Hibernate

May 21, 2015 By j2eereference Leave a Comment

Setting up Hibernate

In this article let’s see how to setup development environment to use hibernate framework with eclipse.

Step1 :

  • Download hibernate jar files: which are required to use hibernate framework. You can download latest version of hibernate jar files from:http://hibernate.org/orm/downloads/

pic1

  • Extract zip file that you downloaded. Inside extracted files:
    •  You can find hibernate-core-5.0.0.Beta2 which is main jar file that is required to use hibernate library.
    • “Lib” folder: contains jars that hibernate requires. It has dependencies of hibernate. Jars that are essential are in the ‘required’ folder and we will also use JPA jar(you can find it within “jpa” folder)

 

Step 2:

  • Open your eclipse: Let’s create new java project with name “FirstHibernateProject”

pic2

  • Right click on project select properties. Within properties go to Java build path and select libraries tab.

pic3

 

  • You can create new library with all required jars, so that you don’t have add jar files each when you are working with hibernate. You can just include this library whenever you are working with hibernate
  • To create new library:
    • Click on Add Library tab and select user library.
    • Click on new and specify library name and click Ok.
  • I have created library with name hibernate (Refer below picture).

pic4

  • After creating library, the next step is to add jar files. Click on “Add JARs”. Select main jar file, required and JPA jar files from extracted files. Click on ok.

pic5

  • Select user library that you created and click on finish

pic6

  • Now you can see that hibernate library is added to your project with all the required jars.

 

Step 3:

  • Before configuring hibernates, prerequisites are:
    • You must have database installed in your machine. So that, we can configure hibernate to connect to database. You can have any database available and configure hibernate to connect to database.
    • Hibernate internally uses JDBC driver to connect to database. So depending on database, you have to provide hibernate the JDBC driver, So that it can use that driver to connect to database.
  • Add your JDBC jar file to a project (Got o properties->Java build path-> libraries-> Add external jars): This will help hibernate to connect to database that you have installed in your machine.

 

Step 4:

  • If you want to change hibernate configuration to another database, you will have to do two things:
    • Install database in your machine.
    • Provide JDBC for that database to hibernate.

This is all the ground work required to configure project that uses hibernate.

We created project, added hibernate jars and JDBC for the database.

Now you are all set to write code that uses hibernate.

Filed Under: Hibernate

Why Hibernate

May 18, 2015 By j2eereference Leave a Comment

Hibernate has started as ORM(Object Relational Mapping) tool. Now lets understand what is the problem that hibernate is going to solve or what are the benefits of using hibernate with an example .

Let’s take an example of inserting Employee data in a table.

Employee Table

Emp_ID Emp_Name Phone_Number Address

 

Employee Class

And we have a Employee object corresponding to the employee table as  below,

Employee
EmplId
EmpName
PhoneNum
Address

Consider we have 5 records to be inserted into the table from the employee object list.

We need to do the following steps for inserting the Employee details into the table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Employee emp[]=new Employee[5];
for(int i=0;i&lt;5;i++)
{
        try {
            String url = "jdbc:msql://200.210.220.1:1114/Demo";
            Connection conn = DriverManager.getConnection(url,"","");
            Statement st = conn.createStatement();
            st.executeUpdate("INSERT INTO Employee" +
                "VALUES (emp[i].getEmplId(), emp[i].empName, emp[i].poneNumber, emp[i].address)");            
            conn.close();
        } catch (Exception e) {
          }
  
}

Step1 : Iterate the list

step2:Get values of each property from the individual objects using the getter method and save it into a variable

Step3 : create a sql statement for inserting into the Employee table

Step 4: Execute the query.

The same way for retrieving the data we have to do the following steps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Employee emp;
try {
            String url = "jdbc:msql://200.210.220.1:1114/Demo";
            Connection conn = DriverManager.getConnection(url,"","");
            Statement st = conn.createStatement();
            ResultSet rs=st.executeQuery("Select * from Employee");
            while(rs.next())
            {
               emp.setEmplId(rs.get("Emp_ID"));
               emp.setEmpName(rs.get("Emp_Name"));
               emp.setPoneNumber(rs.get("Phone_Number"));
               emp.setAddress(rs.get("Address"));
            }
            conn.close();
        } catch (Exception e) {
          }

execute select query

Get individual database column values and set it in the newly created Employee object

eg: Employee employee=new Employee();

employee.setEmplName(resultSet.get(“Emp_Name”));

Here also we are doing the mapping manually..

Problem here is that we have object in java but not in database level. So we face following problems:

    • Mapping variable to column

To insert employee object into database we need to manually map every member variable to column. If we add new column in database or new field in class, we need to make changes in code to map this new field to column and if you are retrieving data you have to set values for these new fields.

    • Mapping relationship

Let’s say an employee object has a reference to a address object. Now I have to map employee to employee table and address to address table and if dependency exist between these two I have to handle that by creating Foreign Key and Primary Key and mapping Foreign Key of employee to Primary Key of address table. This relationship has to be taken care of.

    • Mapping changes to object state

Lets say you retrieve one employee object from database and set it to employee object in java. If we have changed phNo of employee, the state of object has changed. To update this changes on database, I have to write update sequel query and set values depending on the values that have changed. updating object state on database have to be handeled manually.

    • Data type conversion

Lets say I want keep track of whether an employee is a good performer or not. In java we simply make use of Boolean variable and set to either true or false. But there is no Boolean variable at db level so we can use either char(Y/N) or int(1/0) to indicate performance. So we need to handle this data type conversion while inserting employee object into database and while retrieving and setting it to object.

Hibernate came into picture to reduce this gap between Relational database and object and it helps relational to object mapping .

Advantages of using Hibernate

There are many advantages of using hibernate when comparing with typical JDBC,

1) As Hibernate is set of Objects it helps you to avoid SQL, you don’t need to learn SQL language.You can treat TABLE as an Object .

2) Powerful object-oriented hibernate query language .

3) Maps Java Beans to tables,

4) Descriptive O/R Mapping through mapping file.

5) Automatic primary key generation

6) Hibernatre is database independent,It is not specific for a particular data base. The same code will work for all data bases like ORACLE,SQLServer,MySQL etc. If you to change the database  all you need to do is just change the configuration file.

7) Query optimization:  If you use Criteria Quires in Hibernate then hibernate take of the query performance. In case of JDBC you need to tune your queries.

8) First level caching and Second level caching which has vital role in the performance.

9)  We can utilize Inheritance concept

10) We can make use of User defined data type .In case of DB, only some database offer this feature, but if you migrate to other database it will be difficult.

Filed Under: Hibernate

Hibernate Query cache

October 17, 2012 By j2eereference Leave a Comment

Query caching is one of the important features provided by Hibernate. I have explained the first level and second level caching in my previous article ( First level caching using hibernate, Second level caching )  ,When we need a particular query result has to be cached for future reference we can use query caching,

Let’s see how to configure query caching.

hibernate.cfg.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</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>
        <!-- Second-level cache  -->        
        <property name="cache.use_query_cache">true</property>
        <property name="cache.use_second_level_cache">true</property>      
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>        
        <property name="hbm2ddl.auto">validate</property>
         <mapping/>
    </session-factory>
</hibernate-configuration>

Here we are adding the following lines to use query caching.

XHTML
1
2
3
<property name="cache.use_query_cache">true</property>
        <property name="cache.use_second_level_cache">true</property>      
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

Entity class settings

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.j2eereference.hibernate.queryCaching;
 
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
 
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "employee")
public class Employee {
 
private int emp_id;
private String emp_name;
 
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
 
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
 
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
 
}

We have to tell hibernate that a particular query result has to be set in the cache for future use.  We can do this configuration as below .

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.j2eereference.hibernate.queryCaching;
 
import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class QueryCache {
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
 
Query query = session
.createQuery("from Employee emp where emp.emp_id=1");
query.setCacheable(true);
List employees = query.list();
session.getTransaction().commit();
 
Session session2 = sessionFactory.openSession();
session2.beginTransaction();
 
Query query2 = session2
.createQuery("from Employee emp where emp.emp_id=1");
query2.setCacheable(true);
List employees2 = query2.list();
 
session2.getTransaction().commit();
}
}

Output

MS DOS
1
2
3
4
5
6
Oct 16, 2012 8:49:30 PM org.hibernate.cache.StandardQueryCache
INFO: starting query cache at region: org.hibernate.cache.StandardQueryCache
Oct 16, 2012 8:49:30 PM org.hibernate.cache.EhCacheProvider buildCache
WARNING: Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: select employee0_.emp_id as emp1_0_, employee0_.emp_name as emp2_0_ from employee
employee0_ where employee0_.emp_id=1

Here you can notice that hibernate has hit the DB only once . The second result is fetching from the cache.

setCacheable  method is performing two roles.

  • If querycache is not already having the value,  go to the database get the result, set the queryCache
  • For getting the queryCache without hitting the DB

Now lets see how the QueryCache is working with the below code .

I have explained the first level caching in my previous article ( First level caching using hibernate )

Filed Under: Hibernate

Second level caching in Hibernate

October 15, 2012 By j2eereference Leave a Comment

Second level caching in Hibernate :

I have explained the first level caching in my previous article ( First level caching using hibernate ) . Now lets see how hibernate provide the second level caching.

We know that first level/Default  caching is implemented on session. That means if we close the session object and fetching the same record using different session,Hibernate will hit the DB again .

Hibernate provides an option to set the second level caching also through which hibernate make use of cache across the sessions. Now lets see how can we configure the second level caching .

hibernate.cfg.xml

Below is the default configuration for disabling the second level caching

<property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

We have to change this  provider class to one of the class which hibernate is supporting .

Here we will take an example to set it as Ehcache.

 

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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/myDB</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</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>
        <!-- Second-level cache  -->        
        <property name="cache.use_second_level_cache">true</property>
        <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>        
        <property name="hbm2ddl.auto">validate</property>
         <mapping/>
    </session-factory>
</hibernate-configuration>

Two lines mentioned below are required to set the second level cache.

<property name=”cache.use_second_level_cache”>true</property>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>

In order to use Ehcache we have to download ehcahe.jar file .

Configure the entity to get cached:

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
 
@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "employee")
public class Employee {
 
private int emp_id;
private String emp_name;
 
@Id
@GeneratedValue
@Column(name = "emp_id")
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
 
@Column(name = "emp_name")
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
 
}

Here we have added two annotations for setting the cache for the Employee entity

@Cache

And

@ Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

There are different values for the usage attribute . Here we are using the Employee entity only to read records. So i am setting as READ_ONLY.

If this is Read and write , u can set it as READ_WRITE

Now lets see the code which uses the second level caching of hibernate

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class SecondLevelCache {
 
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
SessionFactory sessionFactory = config.configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Employee emp1 = (Employee) session.get(Employee.class, 1);
session.getTransaction().commit();
 
Session session2 = sessionFactory.openSession();
session.beginTransaction();
Employee emp2 = (Employee) session2.get(Employee.class, 1);
session.getTransaction().commit();
session.close();
}
}

Console output

MS DOS
1
2
3
4
5
6
7
INFO: Hibernate Validator not found: ignoring
Oct 15, 2012 7:29:51 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: table found: invoicetracker.employee
Oct 15, 2012 7:29:51 AM org.hibernate.tool.hbm2ddl.TableMetadata
INFO: columns: [emp_name, emp_id]
Hibernate: select employee0_.emp_id as emp1_0_0_, employee0_.emp_name as emp2_0_0_ from employee
employee0_ where employee0_.emp_id=?

Here you can notice that hibernate generated only one query to get the data using two separate session objects. If we are not configuring the second level caching hibernate will hit the DB again.

Filed Under: Hibernate

  • Page 1
  • Page 2
  • Next Page »

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.