Unit 3 FSD
Unit 3 FSD
Design and
implement a simple entity program for employee class.
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 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" +
lastName + ", email=" + email + "]";
}
}
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
// Create an EntityManager
EntityManager em = emf.createEntityManager();
// Begin a transaction
em.getTransaction().begin();
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
}
Querying entities can be done using JPQL (Java Persistence Query Language). Let's query
the entities we created above.
Querying Entities:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;
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();
}
}
@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<>();
public Department() {
}
Employee.java
import javax.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
public Employee() {
}
em.getTransaction().begin();
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;
public Department() {
}
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;
public Employee() {
}
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
em.getTransaction().begin();
department.addEmployee(emp1);
department.addEmployee(emp2);
em.persist(department);
em.getTransaction().commit();
em.close();
emf.close();
}
}
• Unidirectional One-to-Many:
• Bidirectional One-to-Many:
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: