Using JPA to Persist Data and Manage Relationships


Java Persistence API (JPA) is a standard for persisting data in Java applications. It provides annotations and interfaces to manage relational data in an object-oriented way. This article will guide you through using JPA to persist data and configure relationships such as One-to-One, One-to-Many, and Many-to-Many.

Step 1: Setting Up JPA

To use JPA, you need to include a JPA implementation such as Hibernate or EclipseLink in your project. Below is an example of setting up Hibernate with Maven:

            <dependency>
                <groupId>javax.persistence</groupId>
                <artifactId>javax.persistence-api</artifactId>
                <version>2.2</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.6.0.Final</version>
            </dependency>
        

Also, configure the persistence.xml file:

            <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
                <persistence-unit name="examplePU">
                    <properties>
                        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_example"/>
                        <property name="javax.persistence.jdbc.user" value="root"/>
                        <property name="javax.persistence.jdbc.password" value="password"/>
                        <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
                        <property name="hibernate.hbm2ddl.auto" value="update"/>
                        <property name="hibernate.show_sql" value="true"/>
                    </properties>
                </persistence-unit>
            </persistence>
        

Step 2: Persisting Data Using JPA

JPA uses the @Entity annotation to define a class as an entity. Below is an example of an entity class:

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

 @Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private double price;

    // Getters and setters
    public int getId() {
         return id;
    }

    public void setId(int 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;
    }
 }
        

To persist an object, use the EntityManager:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

 public class MainApp {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU");
        EntityManager em = emf.createEntityManager();

        Product product = new Product();
        product.setName("Laptop");
        product.setPrice(1200.00);

        em.getTransaction().begin();
        em.persist(product);
        em.getTransaction().commit();

        em.close();
        emf.close();
    }
}
        

Step 3: Mapping Relationships

JPA allows you to define relationships between entities using annotations such as @OneToOne, @OneToMany, and @ManyToMany.

One-to-One Relationship

A one-to-one relationship connects one entity to another. For example, a `User` may have one `Profile`:

import javax.persistence.*;

 @Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String username;

     @OneToOne(cascade = CascadeType.ALL)
     private Profile profile;

    // Getters and setters
    // ...
 }

@Entity
public class Profile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String bio;

    // Getters and setters
    // ...
}
        

One-to-Many Relationship

A one-to-many relationship connects one entity to multiple others. For example, a `Department` may have multiple `Employees`:

@Entity
 public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
    private List employees;

    // Getters and setters
    // ...
}

@Entity
public class Employee {
     @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToOne
    private Department department;

    // Getters and setters
    // ...
}
        

Many-to-Many Relationship

A many-to-many relationship connects multiple entities to each other. For example, `Student` and `Course`:

@Entity
public class Student {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToMany
    @JoinTable(
        name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id")
     )
    private List courses;

    // Getters and setters
    // ...
}

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String title;

    @ManyToMany(mappedBy = "courses")
    private List students;

    // Getters and setters
    // ...
}
        

Conclusion

JPA simplifies data persistence and management of relationships in Java applications. By using annotations like @OneToOne, @OneToMany, and @ManyToMany, developers can model complex relational structures effectively. JPA's abstraction over SQL helps maintain a clean and modular application architecture.





Advertisement