Java perseverance with JPA and Hibernate: Persisting information to a database


In this second half of the Java persistence with JPA and Hibernate tutorial, we move previous concepts and begin composing code that persists information to and from a relational database using JPA with Hibernate. We’ll begin by configuring an example application to utilize Hibernate as the JPA supplier, then quickly configure the EntityManager and compose 2 classes that we want to continue to the database: Schedule and Author. Finally, we’ll write a simple application that pulls together all the application elements and effectively persists our two entities to the database.You’ll learn how to

: Configure a Java application to

  • use Hibernate as your JPA supplier. Configure JPA’s EntityManager
  • . Produce a basic JPA domain design representing 2 classes with a one-to-many relationship. Use repositories to easily separate persistence reasoning from your application code. Write, construct, and run the example application using
  • JPA to get in touch with a relational database. You’ll likewise get started with JPA Question Language(JPQL)and

    use it to execute a couple of simple database operations on the example application.The total source code for the example application can be discovered here. If you have not read the first half of this tutorial, we advise doing that before you continue.Configuring Hibernate To keep things easy, we’re going to use the embedded H2 database for both advancement and runtime examples. You can alter the JDBC

    URL in the EntityManager

    to point to any database you wish.Start by examining the Maven POM declare the project, shown in Listing 1. Listing 1. pom.xml< project xmlns =""xmlns: xsi ="" xsi: schemaLocation=""> 4.0.0 com.infoworld jpa-example container 1.0-SNAPSHOT jpa-example 21 6.3.1. Final org.apache.maven.plugins maven-compiler-plugin 2.0.2$ $java.version org.apache.maven.plugins maven-jar-plugin true lib / com.infoworld.jpa.JpaExample org.apache.maven.plugins maven-dependency-plugin copy install copy-dependencies $/ lib org.hibernate hibernate-core$ jakarta.persistence jakarta.persistence-api 3.1.0 jakarta.platform jakarta.jakartaee-api 9.1.0 com.h2database h2 2.2.224 runtime jakarta.json.bind jakarta.json.bind-api 3.0.0 org.eclipse yasson 3.0.3 runtime We’ll develop this project using Java 21 and Hibernate variation 6.3, which was the most current version as of this writing . Plugins in the construct node will set the Java compilation variation, make the resulting JAR file executable, and guarantee that all reliances are copied to a lib folder so that the executable container can run. We include the following reliances: Hibernate’s core functionality: hibernate-core The JPA API: hibernate-jpa-2.1-api The embedded H2 database: h2 Keep in mind that H2’s scope is set to runtime so that we can utilize it when we run our code. Setting up the EntityManager Recall that our JPA ‘s EntityManager is driven by the persistence.xml file. Listing 2 shows the contents of this file.Listing 2 ./ resources/persistence. xml org.hibernate.jpa.HibernatePersistenceProvider Although we are utilizing persistence.xml,

    • you might attain a comparable configuration
    • with an annotated EntityManager. Because case
    • , you would use the @PersistenceContext(unitName=” Books “)annotation.The persistence.xml file begins with a determination node that can include one or

    more determination units. A persistence-unit has a name, which we’ll utilize later on when we create the EntityManager, and it defines the qualities of that unit.

  • In this case, we configure properties in this system to do the following: Define HibernatePersistenceProvider, so the

    application knows we’re using Hibernate as our JPA company. Specify the database setup via JDBC. In this case, we’re utilizing an in-memory H2 circumstances. Configure Hibernate, consisting of setting the Hibernate dialect to H2Dialect, so that Hibernate understands how to interact with the H2 database. Note that JPA will automatically scan and find your annotated entity classes. The domain model For this application, we’re modeling a Book class and an Author class. These entities have a one-to-many relationship, meaning that a book can only be written by a

    • single author, however an author can write lots of books. Figure 1 shows this domain design. Steven Haines Figure 1.
    • Domain design for a JPA/Hibernate application with two entities. When we talk about database tables, we normally discuss a”information design

    ,”however when we speak about Java entities and their relationships, we typically describe it as a”domain model.

    “Designing the Book class Let’s start with our entities. Noting 3 reveals the source code for the Book class.Listing 3. package com.infoworld.jpa.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.NamedQueries; import jakarta.persistence.NamedQuery; import jakarta.persistence.Table; @Entity @Table(name=”BOOK”)@NamedQueries(@NamedQuery(name= “Book.findByName”, query =” SELECT b FROM Book b WHERE name” ), @NamedQuery(name<) public class Book p>

    )personal Author author; public

    Book( ) public Book(Integer id, String name ) public Book (String name); public Integer getId()return id; public space setId(Integer id) public String getName() public void setName( String name) = name; public Author getAuthor () return author; public void setAuthor(Author author) @Override public String toString( ) This Book is a simple POJO (plain old Java object)that handles 3 properties: id: The main secret, or identifier, of the book. name: The name, or title, of the book. author: The author who composed the book. The class itself is annotated with three annotations: @Entity: Recognizes the Book as a JPA entity. @Table: Overrides the name of the table to which this entity will be persisted. In this case we define the table name as BOOK. @NamedQueries: Allows you to define JPA Question Language inquiries that can later on be recovered and executed by the EntityManager. About JPA Query Language(JPQL )JPQL resembles SQL, however instead of operating on database column names, it operates on entities, their fields, and their relationships. JPA refers to these questions as working on top of an”abstract schema,”which gets equated to a correct database schema. Entities are mapped to that database schema

  • . Here’s the format for a basic JPQL inquiry: SELECT returnedEntity FROM entityName var WHERE whereClause The
  • Book.findAll inquiry is defined as SELECT b FROM Book

    b, in which “Schedule” is the name of the entity and”b”is the variable name

  • assigned to”Book.
  • “This is comparable to the SQL SELECT * FROM BOOK.The Book.findByName uses a called criterion,”name,” as in: CHOOSE b FROM Book b WHERE
  • : name Specifications can be referenced by name or by position. When referencing a parameter by name, you define the
  • name your question expects, such as”name”or”

    bookName, “prefaced by a”:”. If, rather, you wished to reference the name by position, you could change”: name” with”? 1″. When performing the question, you would set the specification with position of” 1″. Binding the book name to “MyBook “is equivalent to the following SQL: SELECT * FROM BOOK WHERE name=’MyBook ‘The Book’s id quality is annotated with both @Id and @GeneratedValue. The @Id annotation identifies the id

    as the main secret of the Book, which will fix to the main key of the underlying database. The @GeneratedValue annotation informs JPA that the database should generate the primary key when the entity is persisted to the

    database. Due to the fact that we have not specified a @Column annotation, the id

    will be mapped to the same column name,”id.”


    Leave a Reply

    Your email address will not be published. Required fields are marked *