Hibernate Named Query

By | | Updated : 2021-07-09 | Viewed : 0 times

Hibernate Named Query

The Current tutorial guides us about the Named Query in Hibernate with examples. Let\'s start to learn the usage of the Named Query in Hibernate.

Named Query In Hibernate

Technically speaking it is represents the various query strings and initiated when we create the query object using session.createQuery() method in hibernate.

Named Query in Hibernate makes the java code cleaner. Using this named query in hibernate, query strings will be written outside of the class. So it is highly readable and maintainable. The named query looks like below.

Example of Named Query in Hibernate
@NamedQueries(
	{
		@NamedQuery(
				name = "findPersonByName",
				query = "from Person p where p.firstName = :firstName"
		)
	}
)

Hibernate Named Query Example

In the implementation of Named first, we need to add required queries in entity class as given below.

Person.java
@NamedQueries(
	{
		@NamedQuery(
				name = "findPersonByName",
				query = "from Person p where p.firstName = :firstName"
		)
	}
)

@Entity
@Table(name = "person")
public class Person {

	@Id
	@GeneratedValue
	@Column(name = "PERSON_ID")
	private Long id;

	@Column(name = "PERSON_FIRST_NAME")
	private String firstName;

	@Column(name = "PERSON_LAST_NAME")
	private String lastName;

	@Column(name = "PERSON_GENDER")
	private String gender;



}

Now we will fetch the data using Named Query in hibernate. Please notice below the given code snippet.

MainClient.java
public class MainClient {

	public static void main(String[] args) {

		System.out.println("Main method@MainClient");

		try {

			// Get Session
			Session session = HibernateUtil.getSessionFactory().openSession();
			System.out.println("Session is created");

			// start transaction
			Transaction tx = session.beginTransaction();
			TypedQuery query = session.getNamedQuery("findPersonByName");
			query.setParameter("firstName","William");

			List<Person> persons=query.getResultList();

			Iterator<Person> itr = persons.iterator();
			while(itr.hasNext()){
				Person p = itr.next();
				System.out.println(p.getFirstName());
				System.out.println(p.getLastName());
			}
			tx.commit();
			//session.close();
			System.out.println("Session is closed");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

To get the entire code for this example, you can verify the Github repoHibernate-NamedQuery-Example-App

Leave A Reply