Named query with entity in JPA

This is an example of how to create a named query with an entity in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. A named query is a predefined query that you create and associate with a container-managed entity. The named queries are stored on the EntityManager. At run time, you can use the EntityManager to acquire, configure, and execute a named query. Here we create an entity with a named query and use in with EntityManager.

The Employee class

The Employee class is an entity class, annotated with the javax.persistence.Entity annotation. It has a named query, in the @NamedQuery annotation, where we set the name of the query and the sql query. It uses the @Id annotation to define its id property, and the @GeneratedValue annotation with strategy set to GenerationType.AUTO so that the id gets auto-generated values. In another property, it uses the @OneToMany annotation to define a one-to-many relationship to another entity. With the @JoinTable it creates a join between the two entities, defining the columns to be joined and the name of the join table.

package com.javacodegeeks.snippets.enterprise;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;


  query="SELECT e FROM Employee e " +

  "WHERE = ?1")
public class Employee {
	private Long id;
    private String name;
    private String surname;
    private String title;
    private Date created;
    @JoinTable(name = "EMP_PHONE", joinColumns = @JoinColumn(name = "EMP_ID"), inverseJoinColumns = @JoinColumn(name = "PHONE_ID"))
    private Collection<Phone> phones;
    private Department department;
	public Long getId() {
		return id;
	public void setId(Long id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getSurname() {
		return surname;
	public void setSurname(String surname) {
		this.surname = surname;
	public String getTitle() {
		return title;
	public void setTitle(String title) {
		this.title = title;
	public Date getCreated() {
		return created;
	public void setCreated(Date created) {
		this.created = created;
	public void addPhone(Phone phone) {
		if (phones==null) {
			phones = new ArrayList<Phone>();
		if (!phones.contains(phone)) {

	public Collection<Phone> getPhones() {
		return phones;
	public Department getDepartment() {

  return department;
    public void setDepartment(Department department) {

  this.department = department;
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", surname=" + surname
				+ ", title=" + title + ", phones=" + phones + "]";


The NamedQueryWithEntityInJPA class

In the NamedQueryWithEntityInJPA class we create we create an EntityManagerFactory interface to interact with the entity manager factory for MyPeristenceUnit, that is defined in persistence.xml file. We create an EntityManager, using the createEntityManager() API method. Then, we create a new Employee object. The new object is writen to the database, using the persist(java.lang.Object entity) API method of EntityManager. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a method so that a transaction begins and ends. The object can be retrieved using the named query, in the createNamedQuery(java.lang.String name) API method of EntityManager.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class NamedQueryWithEntityInJPA {
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		EntityManager em = emf.createEntityManager();
		Employee employee1 = new Employee();
		employee1.setTitle("QA Engineer");
		employee1.setCreated(new Date());

		Employee employee2 = new Employee();
		employee2.setTitle("QA Engineer");
		employee2.setCreated(new Date());
		Query query = em.createNamedQuery("findEmployeeByName");
		query.setParameter(1, "Jack");
		List<Employee> employees = (List<Employee>) query.getResultList();
		System.out.println("employees " + employees);



<persistence xmlns=""
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="" value="update" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="jcg" />
			<property name="hibernate.connection.password" value="jcg" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" />


employees [Employee [id=1, name=Jack, surname=Thomson, title=QA Engineer, phones=null]]

This was an example of how to create a named query with an entity in JPA.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Back to top button