0% found this document useful (0 votes)
16 views18 pages

Unit 3 FSD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views18 pages

Unit 3 FSD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Define JPA. Explain the properties of an Entities objects.

Design and
implement a simple entity program for employee class.

Java Persistence API (JPA) is a specification for managing relational data in


Java applications. It provides a standardized way to map Java objects to
database tables and manage their persistent state. JPA is part of the Java EE
(Enterprise Edition) specification but can also be used in Java SE (Standard
Edition) applications. It abstracts the underlying data access implementations
and provides an easy-to-use API for interacting with databases.

Properties of Entity Objects

Entity objects in JPA are plain old Java objects (POJOs) that are mapped to
database tables. They have the following properties:

1. Entity Annotation:
o An entity class is annotated with @Entity to indicate that it is a
JPA entity.
2. Table Mapping:
o The @Table annotation specifies the database table to which the
entity is mapped.
3. Primary Key:
o Each entity must have a primary key, which is annotated with @Id.
The primary key can be a simple or composite key.
4. Field Mapping:
o Fields of the entity are mapped to columns in the database table
using the @Column annotation.
5. Constructors:
o An entity class must have a no-argument constructor. It can also
have parameterized constructors for convenience.
6. Getters and Setters:
o Properties of the entity are accessed and modified using getter and
setter methods.
7. Serializable:
o Entity classes should implement the Serializable interface to
allow for serialization of the entity objects.
8. Relationships:
o Entities can have relationships with other entities, such as one-to-
one, one-to-many, and many-to-many. These relationships are
managed using annotations like @OneToOne, @OneToMany,
@ManyToOne, and @ManyToMany.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import java.io.Serializable;

@Entity
@Table(name = "employees")
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "first_name", nullable = false)


private String firstName;

@Column(name = "last_name", nullable = false)


private String lastName;

@Column(name = "email", nullable = false, unique = true)


private String email;

// No-argument constructor
public Employee() {}

// Parameterized constructor
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getters and Setters
public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" +
lastName + ", email=" + email + "]";
}
}

Demonstrate the concept of crud operations on data in JPA.


Explain the steps for creating the Hibernate application.

Explain the purpose of EntityManager in JPA.

The EntityManager is a crucial component in Java Persistence API (JPA)


responsible for managing the lifecycle of entities and performing database
operations. Here are the primary purposes of the EntityManager:

1. Managing Entity Lifecycle:


o The EntityManager manages the lifecycle of entity instances,
including their creation, updating, and deletion. It transitions
entities between different states (new, managed, detached,
removed) based on the operations performed.
2. Persisting Entities:
o The persist method is used to insert a new entity into the
database. This operation transitions a new entity instance from the
new state to the managed state, making it persistent and
synchronized with the database.
3. Querying the Database:
o The EntityManager provides methods to create and execute
queries to retrieve entities from the database. This can be done
using JPQL (Java Persistence Query Language), native SQL, or the
Criteria API. Methods like createQuery,
createNamedQuery, and createNativeQuery facilitate
these operations.
4. Transaction Management:
o The EntityManager is typically used within a transactional
context. It ensures that operations on entities are performed within
transactions, maintaining data integrity and consistency. Methods
like getTransaction (for resource-local transactions) allow for
explicit transaction control.
5. Managing Entity Relationships:
o The EntityManager handles the management of relationships
between entities. This includes cascading operations (e.g.,
cascading persist, merge, remove) and ensuring that associations
are properly synchronized with the database.

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

public class EntityManagerExample {


public static void main(String[] args) {
// Create an EntityManagerFactory for the persistence unit
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("my-persistence-unit");

// Create an EntityManager
EntityManager em = emf.createEntityManager();

// Begin a transaction
em.getTransaction().begin();

// Create a new Employee entity


Employee employee = new Employee("John Doe", "IT", 75000);

// Persist the entity


em.persist(employee);

// Commit the transaction


em.getTransaction().commit();

// Retrieve an entity by primary key


Employee foundEmployee = em.find(Employee.class,
employee.getId());
System.out.println("Found Employee: " + foundEmployee);

// Close the EntityManager


em.close();

// Close the EntityManagerFactory


emf.close();
}
}
Explain the following with an program example:
i.Entity relationship ii. Querying Entities

i. Entity Relationship

Entity relationships in JPA are used to define how entities are related to each other. The main
types of relationships are:

• One-to-One
• One-to-Many
• Many-to-One
• Many-to-Many

1. One-to-One Relationship
A one-to-one relationship is a relationship where each entity instance
is associated with one
instance of another entity.

Example

import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
// Getters and Setters
}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String street;
private String city;
@OneToOne(mappedBy = "address")
private User user;
// Getters and Setters
}

2. One-to-Many Relationship
A one-to-many relationship is a relationship where one entity instance
is associated with
multiple instances of another entity.
Example

import javax.persistence.*;
import java.util.List;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department", cascade =
CascadeType.ALL)
private List<Employee> employees;
// Getters and Setters
}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and Setters
}
3. Many-to-One Relationship
A many-to-one relationship is the inverse of a one-to-many
relationship where multiple
instances of one entity are associated with one instance of another
entity. This is typically represented using the @ManyToOne
annotation on the child entity.
Example
The Employee class above with the @ManyToOne annotation
demonstrates a many-to-one
relationship with the Department entity.

4. Many-to-Many Relationship
A many-to-many relationship is a relationship where multiple
instances of one entity are associated with multiple instances of
another entity. This usually involves a join table to hold
the relationships.
Example

import javax.persistence.*;
import java.util.Set;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses;
// Getters and Setters
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
// Getters and Setters
}

ii. Querying Entities

Querying entities can be done using JPQL (Java Persistence Query Language). Let's query
the entities we created above.

Querying Entities:

• A JPQL query SELECT e FROM Employee e WHERE e.department.name =


:deptName is used to retrieve employees from the IT department.
• TypedQuery ensures type safety in query results.
• The parameter :deptName is set to "IT" to filter employees belonging to the IT
department.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;

public class Main {


public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-
persistence-unit");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Department department = new Department("IT");


Employee emp1 = new Employee("Alice");
Employee emp2 = new Employee("Bob");

department.addEmployee(emp1);
department.addEmployee(emp2);

em.persist(department);

em.getTransaction().commit();

// Querying entities
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e
WHERE e.department.name = :deptName", Employee.class);
query.setParameter("deptName", "IT");
List<Employee> employees = query.getResultList();

System.out.println("Employees in IT department:");
for (Employee employee : employees) {
System.out.println(employee.getName());
}

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

Explain One-to-many Entity Relation mapping both in unidirectional and


bidirectional way with an example.

One-to-Many Entity Relationship Mapping in JPA

Unidirectional vs. Bidirectional

In JPA, one-to-many relationships can be mapped in two ways:

1. Unidirectional: Only one side of the relationship is aware of the other.


2. Bidirectional: Both sides of the relationship are aware of each other.
Department.java
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

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

@Column(nullable = false)
private String name;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "department_id") // Foreign key in the Employee table
private List<Employee> employees = new ArrayList<>();

// Constructors, getters, and setters

public Department() {
}

public Department(String name) {


this.name = name;
}

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 List<Employee> getEmployees() {


return employees;
}

public void setEmployees(List<Employee> employees) {


this.employees = employees;
}

public void addEmployee(Employee employee) {


employees.add(employee);
}

public void removeEmployee(Employee employee) {


employees.remove(employee);
}
}

Employee.java
import javax.persistence.*;

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

@Column(nullable = false)
private String name;

// Constructors, getters, and setters

public Employee() {
}

public Employee(String name) {


this.name = name;
}

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;
}
}

Main.java (for Unidirectional)


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

public class Main {


public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-
persistence-unit");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

Department department = new Department("HR");

Employee emp1 = new Employee("John");


Employee emp2 = new Employee("Doe");

department.addEmployee(emp1);
department.addEmployee(emp2);

em.persist(department);

em.getTransaction().commit();

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

Bidirectional One-to-Many
In a bidirectional one-to-many relationship, both the Department entity and the Employee
entity will be aware of each other.

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

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

@Column(nullable = false)
private String name;

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval


= true)
private List<Employee> employees = new ArrayList<>();

// Constructors, getters, and setters

public Department() {
}

public Department(String name) {


this.name = name;
}

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 List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {


this.employees = employees;
}

public void addEmployee(Employee employee) {


employees.add(employee);
employee.setDepartment(this);
}

public void removeEmployee(Employee employee) {


employees.remove(employee);
employee.setDepartment(null);
}
}

import javax.persistence.*;

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

@Column(nullable = false)
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;

// Constructors, getters, and setters

public Employee() {
}

public Employee(String name) {


this.name = name;
}
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 Department getDepartment() {


return department;
}

public void setDepartment(Department department) {


this.department = department;
}
}

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

public class Main {


public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-
persistence-unit");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

Department department = new Department("IT");

Employee emp1 = new Employee("Alice");


Employee emp2 = new Employee("Bob");

department.addEmployee(emp1);
department.addEmployee(emp2);

em.persist(department);

em.getTransaction().commit();

// Query to verify the relationship


Department foundDepartment = em.find(Department.class, department.getId());
System.out.println("Department: " + foundDepartment.getName());
for (Employee e : foundDepartment.getEmployees()) {
System.out.println("Employee: " + e.getName());
}

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

• Unidirectional One-to-Many:

• Department has a collection of Employee entities annotated with @OneToMany and


@JoinColumn to specify the foreign key.
• The Employee class does not reference Department.

• Bidirectional One-to-Many:

• Department has a collection of Employee entities annotated with @OneToMany and


mappedBy to specify the relationship owner.
• Employee references Department with @ManyToOne and @JoinColumn.
• Methods to manage the relationship are included in Department to keep both sides
synchronized.

List some of JPA query methods and write about them.

In JPA, the EntityManager interface provides several methods to create and execute queries
for retrieving and manipulating entity data. Here are some commonly used query methods
along with their descriptions:

1. createQuery(String qlString, Class<T> resultClass)


o Creates a TypedQuery instance for executing a JPQL query string.
o Example: TypedQuery<Employee> query = em.createQuery("SELECT e
FROM Employee e", Employee.class);
2. createNamedQuery(String name, Class<T> resultClass)
o Creates a TypedQuery instance for executing a named query defined in the
entity class.
o Example: TypedQuery<Employee> query =
em.createNamedQuery("Employee.findAll", Employee.class);
3. createNativeQuery(String sqlString)
o Creates a Query instance for executing a native SQL query.
o Example: Query query = em.createNativeQuery("SELECT * FROM
Employee");
4. createNativeQuery(String sqlString, Class resultClass)
o Creates a Query instance for executing a native SQL query and mapping the
results to the specified entity class.
o Example: Query query = em.createNativeQuery("SELECT * FROM
Employee", Employee.class);
5. find(Class<T> entityClass, Object primaryKey)
o Finds an entity by its primary key.
o Example: Employee employee = em.find(Employee.class, 1L);
6. getCriteriaBuilder()
o Returns an instance of CriteriaBuilder for creating criteria queries.
o Example: CriteriaBuilder cb = em.getCriteriaBuilder();
7. getQueryTimeout()
o Gets the query timeout for the Query object.
o Example: int timeout = query.getQueryTimeout();

You might also like