添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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 into the database is the fundamental operation and the entity represents the data entity in the application, and it can typically be mapped to the database table. Inserting the entity involves creating a new record in the database table to store the entity data.

Importance of Inserting Entities

Inserting the entities is essential for persisting data to the database and it can maintain the state of the application data and it can allow the applications to store the user inputs and perform the data processing and also maintains the data consistency across the different transactions.

Key Terminologies:

  • Entity: This can represent a persistent data entity in an application and can often be mapped to a database table. The entity class can be assigned @Entity defined as an entity.
  • Entity Manager : This is the interface that can be used to interact with the persistence context, and can manage the lifecycle of entities, including tasks such as persistence, merge and removal, and querying.
  • Enhancements : Can be used to set off managed entity instances and these entity managers can use persistence to track changes being made to organizations and synchronize them with the database
  • Primary Key (ID): This can be a primary key that can uniquely identify any record in the table and in these entities, the primary key field can be described with @Id and can be a value itself.
  • Mapping annotations: These annotations are @Entity, @Id, @GeneratedValue, @OneToOne, @OneToMany, @ManyToMany. These are used to map entity classes and define relationships between them.
  • Relationships : It can be defined as the entities can have relationships with other entities such as one-to-one, many-to-one, and many-to-many and these are defined using the appropriate annotations.
  • Cascade Types : It can be defined as how entity lifecycles change the propagate from the parent entities to the child entities. Some common cascade types include the ALL, PERSIST, MERGE, REMOVE and REFRESH.
  • Persistence Unit : It is the logical grouping of the entity classes, and it is the configuration settings. It can be defined in the persistance.xml file and typically corresponds to the database.
  • JPQL : It can be defined as Java Persistence Query Language and it is the query language similar to the SQL but the operations on the entity objects rather than the database tables. It can be used to perform the database queries in the JPA.

Steps for Inserting an Entity

Step 1 : We need to create the entity class that can represents the data you want to the persist into the database. Entity class is annotated with @Entity and define the fields of the entity class includes the primary key annotated with @Id .

Example:

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private double price;

// Getters and Setters
}


Step 2 : We can create the EntityManager interface can be used to the interact with persistence context and it can performs the database operations and also obtain the istance of EntityManager from the EntityManagerFactory .

EntityManagerFactory emf= Persistence.createEntityManagerFactory("jpa-example");
EntityManager em= entityManagerFactory.createEntityManager();


Step 3 : Before the performing any database operations begins the transcation to be ensure that the operations are the atomic and consistent and start the new transcation using EntityTranscation interface.

EntityTransaction trs= entityManager.getTransaction();
trs.begin();


Step 4 : We can use the persist( ) method of the EntityManager interface to the insert the entity into the database and this method can be add the entity to persistence context and it can schedule the insert operation for the entity in database up to the transaction commit.

Ex: Persist the Entity

Product product = new Product();
product.setName("Smart Phone");
product.setPrice(15000.0);

entityManager.persist(product);


Step 5: Once complete the database operation then commit the transaction to apply the changes of database. Now, we can commit the transaction using commit() method of the EntityTransaction interface.

Example: Commit the Transaction

transaction.commit();


Step 6 : Close the EntityManager

entityManager.close();

By following the above steps, we can insert the entity into the database using JPA in the Java applications.

Project Implementation:

Step 1 : First, we can create the JPA project using the IntellijIdea named as entity-demo of the project.

Step 2 : Now, we can add the below dependencies into the JPA project.

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>

Once the project creation completed, then the file structure will look like the below image.

Step 3 : Open persistance.xml and put the below code for the MYSQL database configuration of the database.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
  <persistence-unit name="jpa-example" transaction-type="RESOURCE_LOCAL">
    <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 for the creation of the entity and it named as Product.

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

import jakarta.persistence.*;
// Entity annotation specifies that the class is an entity and is mapped to a database table
@Entity
public class Product {
    // Id annotation specifies the primary key of the entity
    // GeneratedValue annotation provides the strategy for generating primary key values
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // Name of the product
    private String name;
    // Price of the product
    private double price;
    // Getter method for retrieving the product id
    public Long getId() {
        return id;
    // Setter method for setting the product id
    public void setId(Long id) {
        this.id = id;
    // Getter method for retrieving the product name
    public String getName() {
        return name;
    // Setter method for setting the product name
    public void setName(String name) {
        this.name = name;
    // Getter method for retrieving the product price
    public double getPrice() {
        return price;
    // Setter method for setting the product price
    public void setPrice(double price) {
        this.price = price;

Step 5: Create the new Java class and named as the Main.

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

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class Main {
    public static void main(String[] args) {
        // Obtain EntityManager instance
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-example");
        EntityManager em = emf.createEntityManager();
        // Begin transaction
        em.getTransaction().begin();
        // Create and persist Product entity
        Product product = new Product();
        product.setName("Laptop");
        product.setPrice(1000.0);
        em.persist(product);
        // Commit transaction
        em.getTransaction().commit();
        // Retrieve the persisted Product entity
        Product persistedProduct = em.find(Product.class, product.getId());
        // Print the details of the persisted Product entity
        System.out.println("Inserted Product Details:");
        System.out.println("ID: " + persistedProduct.getId());
        System.out.println("Name: " + persistedProduct.getName());
        System.out.println("Price: " + persistedProduct.getPrice());
        // Close EntityManager
        em.close();
        emf.close();

pom.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>entity-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>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 done, then run the application and we can get the output like the below image.

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 in Java applications and can provide a variety of
JPA - Entity Introduction
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 EntitiesJPA e
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 mapping it to the corresponding entity objects in the
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 entity of the JPA application.Retrieve the Entity:
JPA - Creating an Entity
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 An
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 the JPA involves the following steps: 1. Retrievin
Difference between JPA and Spring Data JPA
JPA provides specifications for persisting, reading, and maintaining data from Java objects to relational tables in a database. The JPA defines rules and principles for conducting standard interfaces. Spring data repository significantly reduces the extra code necessary to provide a data access layer for multiple persistence stores. Spring Data JPA
How to Set the Schema Name Dynamically in Spring JPA?
Spring JPA provides a convenient way to save Java objects to relational databases. However, it typically assumes that you have a single schema for your database. If you need to work with multiple schemas, you can use a custom naming strategy to set the schema name dynamically. Creating a Custom Naming StrategyTo create a custom naming strategy, you
Spring Boot - Build a Dynamic Full Text Search API Using JPA Queries
A Global Full-Text Entity Search is a search functionality that allows users to find entities such as records or objects within a dataset by searching through the entirety of their content. Global Full-Text Entity Search is like having a super-smart search companion that digs deep into the entire content of entities. Consider the below examples to
Spring Data JPA vs Spring JDBC Template
In this article, we will learn about the difference between Spring Data JPA vs Spring JDBC Template. Spring Data JPATo implement JPA-based repositories, Spring Data JPA, a piece of the Spring Data family, takes out the complexity. With the help of spring data JPA the process of creating Spring-powered applications that support data access technolog
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, batch processing is used to read and write data in bu
Show SQL from Spring Data JPA/Hibernate in Spring Boot
In Spring Boot, Spring Data JPA is part of the larger Spring Data Project that can simplify the development of the data access layers in the spring applications using the Java Persistence API and it can provide a higher-level abstraction over the JPA API. It can reduce the boilerplate code and make it easier to work with the database. Spring Data J
JPA - Criteria GROUP BY Clause
JPA in Java can be called the Java Persistence API. It provides the Criteria API as a programming mechanism for creating queries dynamically. One of these important features is the GROUP BY clause which allows developers to group query results based on specific criteria. GROUP BY ClauseThe Group BY clause of the JPA Criteria API is used to create g
JPA - ORDER BY Clause
JPA in Java can be defined as the Java Persistence API and consists of Java instructions for accessing and managing data between Java objects and related databases. JPA provides ways for us to access object-oriented and complex databases through SQL queries and database connections. There are many clauses in JPA and the ORDER BY clause is one of th
JPA - CRUD
JPA in Java can be called Java Persistence API (JPA) which can simplify the process of working with the database by providing object relationship mapping structure CRUD operations (Create, Read, Update, Delete) are actions especially if it contains database abuse. JPA CRUD operationJPA is a Java specification for Object-Relational Mapping (ORM). It
findBy Methods in Spring Data JPA Repositories
Spring Data JPA abstracts the boilerplate code required to interact with the database, allowing developers to focus more on business logic rather than database connectivity and query formation. The findBy() method, in particular, is a part of the repository layer in Spring Data JPA, enabling developers to construct queries simply by defining method
JPA - Single Table Strategy
JPA in Java can be defined as the Java Persistence API. The Single Table Strategy is a property mapping technique that is used to map a class hierarchy to a single database table. This strategy allows all subclasses to store data in a single database table. Single Table StrategyIn Single Table Strategy, the superclass and all of its subclasses are
JPA - Query Creation from Method Names
In Java, JPA can defined as Java Persistence API can provide a powerful way to interact with databases in Java applications. One of the key features of the JPA is the Query Creation from the Method names and it allows the developers to dynamically create the database queries based on the method names. Creating Queries from Method Names in JPAQuery
JPA - Criteria WHERE Clause
JPA in Java is defined as the Java Persistence API and the Criteria API provides a structured and type-safe way to build dynamic queries at runtime. The WHERE clause is an integral part of any SQL query and allows us to modify records based on specified conditions. Similarly, the WHERE clause in the JPA Criteria API is used to specify filtering cri
JPA - Collection Mapping
In Java, JPA can defined as Java Persistence API. Collection Mapping is a powerful feature that allows developers to map relationships between the entities and collections in the database. It allows the developers to map the collections of the objects from Java to corresponding database structures. Collection MappingCollection Mapping in JPA refers
Spring Data JPA - @Modifying Annotation
@Modifying annotation in Spring Data JPA allows modification queries such as update and delete and enhances the capabilities of the @Query annotation. It enables data transformation actions beyond simple data retrieval, ensuring transaction integrity and improving performance. The @Modifying annotation is used to enhance the @Query annotation so th
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, and AVG. It allows the developers to specify the
JPA - Joined strategy
In Java, JPA is defined as JavaServer Pages, and JPA Joined Strategy is one of the inheritance mapping strategies, and it can be used to map the inheritance to the database tables. In the Joined strategy, each entity class in the hierarchy is mapped to its database table. It is a separate table that is created for the shared attributes. Steps to Im
JPA - Advanced Mappings
JPA in Java is defined as the Java Persistence API and Advanced Mapping in JPA allows developers to define complex relationships and data mappings between entities and database tables. These mappings include One-to-One mapping, One-to-Many, Many-to-One, Many-to-Many relationships. Also, it can embed objects and sequential methods. Steps to Implemen
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 and enhance the code readability of the JPA Applic
JPA - Set Mapping
In Java, JPA is defined as Java Persistence API. The mapping association between the entities is an important aspect of designing database-driven applications. One such mapping is the Set mapping. It establishes the one-to-many relationship between the entities. Set mapping in JPA is used to represent the collection of related entities where each e
JPA - Cascade Persist
In Java, JPA is defined as the Java Persistence API and acts as a bridge between Java objects and a relational database. It simplifies simple data management in Java applications. One of the key features of the JPA is Cascade Persist and it is a mechanism designed to sustain the relevant companies once the parent company becomes sustainable Cascade
JPA - Many-To-Many Mapping
JPA Many-To-Many Mapping provides the many-to-many relationship representing the association between the two entities where each instance of the one entity can be associated with the multiple instances of the other entity. Many-to-many mapping is used when multiple instances of one entity are associated with multiple instances of another entity, an
JPA - Object Relational Mapping
JPA in Java is defined as the Java Persistence API and consists of Java specification for accessing, persisting, and maintaining data between Java objects and related databases One of the main features of JPA is Object Relational Mapping (ORM). This is the bridge between, or we can say the difference between an object-oriented domain model and a re
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 Criteria API allows the developers to create queries us
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 Got It !
Please go through our recently updated Improvement Guidelines before submitting any improvements.
This improvement is locked by another user right now. You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.
You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!
Please go through our recently updated Improvement Guidelines before submitting any improvements.
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.