jpa

Get single object in JPA

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: February 27th, 2019
0 383 2 minutes read

With this example we are going to demonstrate how to get a single object in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications.
 
 
 
 
 
 
 
 
 

Here, we are using JPA to retrieve a single object from the database, as shown below:

The GetSingleObjectInJPA class

InGetSingleObjectInJPA we create anEntityManagerFactory interface to interact with the entity manager factory forMyPeristenceUnit, that is defined inpersistence.xml file. We create an EntityManager, using thecreateEntityManager() API method. Then, we create newEmployee objects. The new objects are written to the database, using thepersist(java.lang.Object entity) API method ofEntityManager. ThegetTransaction().begin() andgetTransaction().commit() methods are used before and after theEntityManager invokes a method so that a transaction begins and ends. AnEmployee object can be retrieved, using thecreateQuery(String qlString) API method of EntityManager, with an sql String query to get a specified employee. Using thesetParameter(int position, java.lang.Object value) method of Query we bind an argument to a positional parameter. Then, using thegetSingleResult() of Query to execute a SELECT query that returns a single untyped result.

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 GetSingleObjectInJPA {@SuppressWarnings("unchecked")public static void main(String[] args) {EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");EntityManager em = emf.createEntityManager();// create the employeesem.getTransaction().begin();for (int i = 0; i < 5; i++) {Employee employee = new Employee();employee.setName("employe_"+i);employee.setSurname("surname_"+i);employee.setTitle("Engineer_"+i);employee.setCreated(new Date());em.persist(employee);}em.getTransaction().commit();// retrieve the employeeslong employeeId = 2;em.getTransaction().begin();Query query = em.createQuery("SELECT e FROM Employee e where id=?1");query.setParameter(1, employeeId);Employee employee = (Employee) query.getSingleResult();System.out.println("Found: " + employee);em.getTransaction().commit();em.close();    emf.close();}}

Employee Class

TheEmployee class is an entity class, annotated with thejavax.persistence.Entity annotation. It uses the@Id annotation to define its id property, and the@GeneratedValue annotation with strategy set toGenerationType.AUTO so that the id gets auto-generated values.

package com.javacodegeeks.snippets.enterprise;import java.util.Date;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Employee {@Id@GeneratedValue(strategy=GenerationType.AUTO)private Long id;    private String name;    private String surname;    private String title;    private Date created;    public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.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;}@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", surname=" + surname+ ", title=" + title + "]";}}

persistence.xml

Want to be a JPA Master ?
Subscribe to our newsletter and download the JPAUltimateGuideright now!
In order to help you master programming with JPA, we have compiled a kick-ass guide with all the major JPA features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"    version="2.0"><persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL"><provider>org.hibernate.ejb.HibernatePersistence</provider><properties><property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /><property name="hibernate.hbm2ddl.auto" 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" /></properties></persistence-unit></persistence>

Output:

Found: Employee [id=2, name=employe_1, surname=surname_1, title=Engineer_1]

 
This was an example of how to get a single object in JPA.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: February 27th, 2019
0 383 2 minutes read
Photo of Ilias Tsagklis

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.