Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views3 pages

Assignment-Mapping in Spring Data JPA

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)
4 views3 pages

Assignment-Mapping in Spring Data JPA

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/ 3

Assignment: Mapping in Spring Data JPA

Objective

Create a console-based Spring Boot application that demonstrates a One-to-Many mapping


between Department and Employee.

Task 1: Project Setup

1. Create a new Spring Boot project using Spring Initializr.


2. Select dependencies:
o Spring Data JPA
o PostgreSQL Driver

Task 2: PostgreSQL Setup

1. Install and start PostgreSQL.


2. Create a database named employee_department_db.
3. Note down:
o Database name
o Username
o Password
o Port (default: 5432).

Task 3: Configure Application

In application.properties:

• Configure database connection (spring.datasource.url, username, password).


• Set Hibernate DDL mode to auto-create tables (spring.jpa.hibernate.ddl-
auto=create).
• Enable SQL logging (spring.jpa.show-sql=true).

Task 4: Entity Design


1. Create an Employee entity with:
o id (Primary Key, auto-generated)
o name
o role
2. Create a Department entity with:
o id (Primary Key, auto-generated)
o name
o One-to-Many relationship with employees (unidirectional).
o Use @JoinColumn so that a department_id foreign key is created in the
Employee table.

Task 5: Repository Layer

1. Create a DepartmentRepository extending JpaRepository.


2. Create an EmployeeRepository extending JpaRepository.
3. Add custom finder methods in repositories:
o In EmployeeRepository:
▪ List<Employee> findByRole(String role);
▪ List<Employee> findByNameContaining(String keyword);
o In DepartmentRepository:
▪ Department findByName(String name);

Task 6: Console Interaction (Runner Class)

1. Implement CommandLineRunner in a separate class.


2. Inside run() method:
o Insert one department with multiple employees.
o Save them into PostgreSQL.
o Retrieve all departments and employees and print them on the console.
o Call custom finder methods and print results on the console.
▪ Example:
▪ Find all employees with role = "Developer".
▪ Find all employees whose name contains "A".
▪ Find department by name "IT Department".
Task 7:

• Accept department and employee details from the console (Scanner) instead of
hardcoding.
• Add more custom queries, e.g.,
o findByRoleAndName(String role, String name)
o findByDepartmentId(Long deptId)

You might also like