JPA is defined as Java Persistence API (JPA) that can simplify the process of the persisting Java objects to the relational databases. Creating the entity in the JPA involves defining the java class that can represent the database table and it can be annotated with the JPA annotations to specify its mapping to the database schema.
Entity Related Annotations
- Entity: This annotation of the java class can indicate that it is the entity and it can represent the tables in the relational database. Example: @Entity
- Table: This annotation that can specifies the details of the database table to which the entity is mapped. Example: @Table
- Id: This annotation can mark the field in the entity as the primary key. Example: @Id
- GeneratedValue: This annotation can be configured the way primary key values are generated for the entity. Example: @GeneratedValue(strategy = GenerationType.IDENTITY)
- Column: This annotation can be specifies the maps of an entity field to the database column. Example: @Column
- Basic Configure: This annotation can specify the default fetch type for an entity field. Example: @Basic(fetch = FetchType.LAZY)
- Transient: This annotation can mark the field in the entity as the transient and it will not be persisted in the database. Example: @Transient
- ManyToOne: This annotation can define the many-to-one relationship between the entities. Example: @ManyToOne
- OneToMany: This annotation can define the one-to-many relationship between the entities. Example: @OneToMany
- OneToOne: This annotation can define the one-to-one relationship between the entities.
- JoinColumn: It can defined as the specifies the mapping of the foreign key column in the relationship. Example: @JoinColumn
- JoinTable: This annotation can be specifies the mapping of the intermediate table in the many to many relationship. Example: @JoinTable
- Getter and Setter Methods: This methods can be used to retrieve and set the values of the entity fields.
Example Project
Step 1: Create the new JPA project using the InteljIdea named as create-entity-demo once create the project then the file structure looks like the below image.
file structureStep 2: Open the open.xml and add the below dependencies into the project.
<!-- 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="example-unit">
<class>Product</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.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 new Entity Java class named as the Product. Go to src > main > java > Product and put the below code.
Java
import jakarta.persistence.*;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Step 5: Create the new Java class named as the MainApp. Go to src > main > java > MainApp and put the below code.
Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.util.List;
public class MainApp {
public static void main(String[] args) {
// Initialize EntityManagerFactory
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("example-unit");
// Create EntityManager
EntityManager entityManager = entityManagerFactory.createEntityManager();
// Persist sample data
persistSampleData(entityManager);
// Display sample data
displaySampleData(entityManager);
// Close EntityManager
entityManager.close();
// Close EntityManagerFactory
entityManagerFactory.close();
}
private static void persistSampleData(EntityManager entityManager) {
// Begin transaction
entityManager.getTransaction().begin();
// Create sample products
Product product1 = new Product();
product1.setName("Product 1");
product1.setPrice(10.99);
Product product2 = new Product();
product2.setName("Product 2");
product2.setPrice(20.99);
// Persist products
entityManager.persist(product1);
entityManager.persist(product2);
// Commit transaction
entityManager.getTransaction().commit();
}
private static void displaySampleData(EntityManager entityManager) {
// Query all products
List<Product> products = entityManager.createQuery("SELECT p FROM Product p", Product.class).getResultList();
// Print product details
System.out.println("Products:");
for (Product product : products) {
System.out.println("ID: " + product.getId() + ", Name: " + product.getName() + ", Price: " + product.getPrice());
}
}
}
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>create-entity-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>create-entity-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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
<build>
<plugins>
</plugins>
</build>
</project>
Step 6: Once the project is completed, run the application then show the ID, name, product and prices of the products as output. Refer the below image for the better understanding of the concept.
outputIf we follow the above procedure, then we can successfully build the JPA application of the demonstration of the creating the entity of the JPA Application.
Conclusion
In JPA, Creating the 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.
Similar Reads
JPA - Deleting an Entity
In Java, JPA can be defined as Java Persistence API, deleting the entity is the crucial operation in managing database records. It can involve removing an object from the database and ensuring the data consistency and integrity of the application. Steps to ImplementDefine Entity: We can define the e
5 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 - Update an Entity
JPA refers to Java Persistence API. In JPA, Updating the entity is a crucial operation when working within the databases. This process involves modifying the attributes of the existing entity and it can persist the changes back to the database.Steps to Update an Entity in JPAUpdating the entity in t
6 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 - Criteria API
In Java, JPA is defined as Java Persistence API, and the Criteria API provides a powerful tool for constructing the queries dynamically at the runtime. Unlike the JPQL (Java Persistence Query Language) which uses the strings to represent the queries programmatically. Criteria API in JPAThe JPA Crite
6 min read
JPA - Criteria Having Clause
The JPA Criteria API in Java provides a systematic way to build dynamic queries at runtime without relying on static string-based queries. The JPA Criteria Having Clause is used to extract query results based on the conditions used on the collected data with aggregation functions such as COUNT, SUM,
6 min read
Spring Data JPA - @Id Annotation
Spring Data JPA is a important part of Spring Boot applications, providing an abstraction over JPA (Java Persistence API) and simplifying database interactions. JPA is a specification that defines a standard way to interact with relational databases in Java, while Hibernate is one of the most widely
3 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO cla
3 min read
What are XML Entities ?
XML is a way to organize information on the internet. It's like a recipe that tells computers how to understand and use the information. Entities in XML are like ingredients in a recipe. They help you define and reuse parts of your information, making it easier to manage and share. What is XML?XML s
8 min read
Hibernate - @GeneratedValue Annotation in JPA
The @GeneratedValue annotation, the name itself suggests that it will generate something. This annotation is generally used in conjunction with the @Id annotation to automatically generate unique values for primary key columns within our database tables. When creating an entity class, we have to spe
3 min read