Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
JPA - Entity Introduction
Next article icon

JPA - Entity Introduction

Last Updated : 02 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Java Persistence API (JPA) can facilitate the development of Java applications by providing a framework for managing relational data in Java applications and JPA is one of the key concepts in entities. Entities can represent and use persistent data stored in a relational database map to corresponding database tables.

Understanding JPA Entities

JPA entities are Java classes that can be mapped to database tables and these classes define the structure of the data and act as a bridge between the object-oriented world of Java and the relational world of the database.

Steps to Create a JPA Entity:

  • Define the java class and it can annotate it with the @Entity to mark it as an entity.
  • Define fields in the class to represent columns in the database table.
  • It can be annotated fields with the appropriate JPA annotations like @OneToOne and @OneToMany etc.
  • It can configure the data source and the persistence unit in the persistance.xml file.
  • It can use the EntityManager to perform the CRUD operations on the entities.

JPA Entity Example Project

We can develop a simple JPA project that can use entity and address entity mapped both of entities that can save the user data into the MYSQL database.

Step 1: Create the new JPA project using the InteljIdea named as a demo once create the project then the file structure looks like the below image.

Project Structure


Step 2: Open the open.xml and add the below dependencies into the project.

XML
<!-- Database Driver (MySQL in this example) --> <dependency>       <groupId>mysql</groupId>       <artifactId>mysql-connector-java</artifactId>       <version>8.0.28</version> </dependency> <dependency>       <groupId>org.hibernate.orm</groupId>       <artifactId>hibernate-core</artifactId>       <version>6.0.2.Final</version> </dependency> <dependency>       <groupId>org.glassfish.jaxb</groupId>       <artifactId>jaxb-runtime</artifactId>       <version>3.0.2</version> </dependency> <dependency>   <groupId>org.junit.jupiter</groupId>   <artifactId>junit-jupiter-api</artifactId>   <version>${junit.version}</version>   <scope>test</scope> </dependency> <dependency>       <groupId>org.junit.jupiter</groupId>       <artifactId>junit-jupiter-engine</artifactId>       <version>${junit.version}</version>       <scope>test</scope> </dependency> 


Step 3: Open the persistence.xml and put the below code into the project and it can configure the database of the project.

XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <persistence xmlns="https://jakarta.ee/xml/ns/persistence"              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"              version="3.0">      <persistence-unit name="jpa-example" transaction-type="RESOURCE_LOCAL">         <class>model.Address</class>         <class>model.User</class>         <properties>             <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>             <property name="jakarta.persistence.jdbc.user" value="root"/>             <property name="jakarta.persistence.jdbc.password" value=""/>             <property name="jakarta.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>             <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>             <property name="hibernate.hbm2ddl.auto" value="update"/>         </properties>      </persistence-unit> </persistence> 


Step 4: Create the Java package named as the model in that package create the Java class named as the User.

Go to src > main > java > model > User and put the below code.

Java
package model; import jakarta.persistence.*;  /**  * Represents a user entity in the application.  */ @Entity public class User {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private Long id; // Unique identifier for the user.      private String name; // The name of the user.      @OneToOne(cascade = CascadeType.ALL)     @JoinColumn(name = "address_id", referencedColumnName = "id")     private Address address; // The address associated with the user.      /**      * Retrieves the unique identifier of the user.      * @return The user's ID.      */     public Long getId() {         return id;     }      /**      * Sets the unique identifier of the user.      * @param id The user's ID.      */     public void setId(Long id) {         this.id = id;     }      /**      * Retrieves the name of the user.      * @return The name of the user.      */     public String getName() {         return name;     }      /**      * Sets the name of the user.      * @param name The name of the user.      */     public void setName(String name) {         this.name = name;     }      /**      * Retrieves the address associated with the user.      * @return The user's address.      */     public Address getAddress() {         return address;     }      /**      * Sets the address associated with the user.      * @param address The user's address.      */     public void setAddress(Address address) {         this.address = address;     } } 


Step 5: Create the one newer Java class named as the Address.

Go to src > main > java > model > Address and put the below code.

Java
package model;  import jakarta.persistence.*; import java.util.List;  /**  * Represents an address entity in the application.  */ @Entity public class Address {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private Long id; // Unique identifier for the address.      private String street; // The street of the address.      private String city; // The city of the address.      @OneToMany(mappedBy = "address", cascade = CascadeType.ALL)     private List<User> users; // The list of users associated with this address.      /**      * Retrieves the unique identifier of the address.      * @return The address ID.      */     public Long getId() {         return id;     }      /**      * Sets the unique identifier of the address.      * @param id The address ID to set.      */     public void setId(Long id) {         this.id = id;     }      /**      * Retrieves the street of the address.      * @return The street of the address.      */     public String getStreet() {         return street;     }      /**      * Sets the street of the address.      * @param street The street to set for the address.      */     public void setStreet(String street) {         this.street = street;     }      /**      * Retrieves the city of the address.      * @return The city of the address.      */     public String getCity() {         return city;     }      /**      * Sets the city of the address.      * @param city The city to set for the address.      */     public void setCity(String city) {         this.city = city;     }      /**      * Retrieves the list of users associated with this address.      * @return The list of users.      */     public List<User> getUsers() {         return users;     }      /**      * Sets the list of users associated with this address.      * @param users The list of users to set.      */     public void setUsers(List<User> users) {         this.users = users;     } } 


Step 6: Create the Main class and put the below code for the Entity manager of the class.

Go to src > main > java > Main and put the below code.

Java
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Persistence; import model.Address; import model.User;  /**  * A class demonstrating basic usage of JPA (Java Persistence API).  */ public class Main {     public static void main(String[] args) {         // Create EntityManagerFactory using persistence unit name         EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-example");          // Create EntityManager         EntityManager em = emf.createEntityManager();          // Create and persist a new user with address         em.getTransaction().begin(); // Begin transaction         Address address = new Address();         address.setStreet("111 Srikakulam");         address.setCity("City");         em.persist(address); // Persist the address entity          User user = new User();         user.setName("Mahesh");         user.setAddress(address);         em.persist(user); // Persist the user entity along with associated address         em.getTransaction().commit(); // Commit transaction          // Retrieve user with associated address         User retrievedUser = em.find(User.class, user.getId());         System.out.println("Retrieved User: " + retrievedUser.getName());         System.out.println("User's Address: " + retrievedUser.getAddress().getStreet() + ", " + retrievedUser.getAddress().getCity());          // Close EntityManager and EntityManagerFactory         em.close();         emf.close();     } } 

pom.xml:

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>      <groupId>org.example</groupId>     <artifactId>demo</artifactId>     <version>1.0-SNAPSHOT</version>     <name>demo</name>      <properties>         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>         <maven.compiler.target>11</maven.compiler.target>         <maven.compiler.source>11</maven.compiler.source>         <junit.version>5.9.2</junit.version>     </properties>      <dependencies>         <dependency>             <groupId>org.hibernate.orm</groupId>             <artifactId>hibernate-core</artifactId>             <version>6.0.2.Final</version>         </dependency>         <dependency>             <groupId>org.glassfish.jaxb</groupId>             <artifactId>jaxb-runtime</artifactId>             <version>3.0.2</version>         </dependency>         <dependency>             <groupId>org.junit.jupiter</groupId>             <artifactId>junit-jupiter-api</artifactId>             <version>${junit.version}</version>             <scope>test</scope>         </dependency>         <dependency>             <groupId>org.junit.jupiter</groupId>             <artifactId>junit-jupiter-engine</artifactId>             <version>${junit.version}</version>             <scope>test</scope>         </dependency>          <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->         <dependency>             <groupId>org.projectlombok</groupId>             <artifactId>lombok</artifactId>             <version>1.18.30</version>             <scope>provided</scope>         </dependency>            <!-- Database Driver (MySQL in this example) -->         <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <version>8.0.28</version>         </dependency>     </dependencies>      <build>         <plugins>         </plugins>     </build> </project> 


Step 7: Once the project is completed, run the application then show the User and address as output. Refer the below image for the better understanding of the concept.

JPA Output

If we follow the above procedure, then we can successfully build the JPA application of the demonstration of the Entity Concept of the JPA.

Conclusion

JPA entities are the fundamental building blocks for the developing the Java applications with database interaction and understanding the entities is the crucial for the effective utilization of the JPA in application development. By following the proper steps and utilizing the appropriate annotations and developers can be seamlessly integrate the entities into the application therefore the improving the code maintainability and database interaction efficiency.


Next Article
JPA - Entity Introduction

M

maheshkadambala
Improve
Article Tags :
  • Advance Java
  • JPA

Similar Reads

    JPA - Introduction
    JPA can be defined as Java Persistence API. It is the Java specification that can provide a standardized way to manage the relational data in Java applications. JPA facilitates the management of the database operations and mapping of the Java objects to database tables by defining the concepts and A
    4 min read
    JPA - Inserting an Entity
    The JPA (Java Persistence API) is a Java specification for accessing, persisting, and maintaining data between Java objects and a relational database. It can provide a framework for assigning Java objects to database tables and simplify database operations in Java applications. Inserting an entity i
    7 min read
    JPA - Finding an Entity
    JPA in Java can be defined as the Java Persistence API(JPA). Entities are the basic building blocks that represent data in a database. Correctly retrieving entities from a database is an important part of any JPA application. Finding an Entity in JPA involves taking data stored in a database and map
    5 min read
    JPA - Introduction to Query Methods
    In Java, JPA can defined as Java Persistence API. It can provide a powerful and intuitive way to interact with the database using object-oriented paradigms. Query Methods Can offer a convenient approach to define database queries directly within the repository and it can reduce the boilerplate code
    5 min read
    JPA - Hibernate Entity Manager
    JPA in Java persistence can be defined as the Java Persistence API, and it plays an important role in communicating between Java objects and related databases Hibernate is one of the most popular JPA implementations. JPA and Hibernate Entity ManagerJPA is a specification for managing relational data
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences