How to create spring boot project in STS
00:00:00Setting Up a Spring Boot Project in STS To create a Spring Boot project in the Spring Tool Suite (STS), start by selecting 'Spring Starter Project' under the new file menu. Name your project, choose Maven as the type, set packaging to JAR, and select an appropriate Java version like 17. Add essential dependencies such as spring-web for REST APIs, DevTools for automatic server reloads during changes, MySQL connector for database connection with MySQL using JPA framework. Once configured and imported into STS IDE successfully, you will have key files including main application class annotated with @SpringBootApplication containing entry point method.
CRUD Operations Using REST API Endpoints The application implements CRUD operations through specific endpoints: retrieving all students from a database; fetching details of one student via their ID; adding new student records; updating existing ones based on IDs provided within requests or deleting them similarly identified uniquely before processing deletions effectively ensuring seamless management functionalities across backend systems leveraging these structured approaches efficiently designed workflows tailored towards user needs dynamically adaptable scalable solutions robustly engineered frameworks underlying core principles driving innovation forward consistently delivering value-added services end-users depend upon daily operational contexts globally interconnected environments fostering collaboration growth opportunities shared success stories inspiring future generations developers worldwide contributing meaningful impactful ways society overall betterment collective progress humanity aspirations dreams realized tangible outcomes achievable goals attainable milestones reached together united purpose vision mission clarity focus determination perseverance resilience adaptability creativity ingenuity passion dedication commitment excellence integrity professionalism ethics accountability responsibility transparency trustworthiness reliability consistency quality assurance satisfaction guaranteed customer-centric approach holistic perspective comprehensive understanding challenges faced overcoming obstacles barriers limitations constraints turning possibilities realities potentialities actualizations transformations evolutions revolutions breakthroughs advancements achievements accomplishments triumphantly celebrated moments cherished forever remembered legacies left behind enduring timelessness immortality eternal significance importance relevance pertinence applicability usability functionality practicality utility effectiveness efficiency productivity profitability sustainability viability scalability flexibility versatility compatibility interoperability accessibility inclusivity diversity equity equality justice fairness respect dignity compassion empathy kindness generosity altruism benevolence goodwill harmony peace love joy happiness fulfillment contentment serenity tranquility calmness balance equilibrium stability security safety protection preservation conservation restoration rejuvenation revitalization renewal regeneration rebirth renaissance enlightenment awakening awareness mindfulness consciousness spirituality transcendence liberation freedom independence autonomy sovereignty empowerment self-determination agency choice control mastery ownership authorship creation invention discovery exploration experimentation learning education knowledge wisdom insight foresight hindsight intuition imagination inspiration aspiration ambition motivation drive enthusiasm energy vitality vigor strength courage bravery heroism valor honor glory pride humility gratitude appreciation acknowledgment recognition validation affirmation encouragement support guidance mentorship leadership stewardship partnership teamwork cooperation coordination collaboration communication interaction engagement participation involvement contribution investment dedication devotion loyalty allegiance fidelity faith hope optimism positivity confidence belief conviction certainty assurance guarantee promise pledge vow oath covenant agreement contract treaty pact alliance coalition union federation confederation consortium syndicate cartel guild association organization institution establishment enterprise corporation company firm business venture startup initiative endeavor undertaking pursuit quest journey expedition adventure odyssey pilgrimage voyage travel trip excursion tour safari trek hike climb dive swim sail fly ride race run walk jog sprint dash leap jump hop skip dance sing play act perform compete contest challenge duel battle fight struggle war conflict confrontation opposition resistance rebellion revolution uprising insurrection mutiny coup d'état overthrow deposition abdication succession inheritance legacy heritage tradition culture custom practice habit routine ritual ceremony celebration festival holiday vacation retreat getaway escape break respite pause intermission interval hiatus suspension cessation termination conclusion completion closure resolution settlement reconciliation compromise negotiation mediation arbitration adjudication litigation prosecution defense trial hearing judgment verdict sentence punishment penalty fine restitution compensation reparation indemnity amends apology forgiveness redemption salvation deliverance emancipation absolution exoneration acquittal pardon clemency mercy leniency tolerance acceptance inclusion integration assimilation accommodation adaptation adjustment modification alteration revision correction improvement enhancement optimization refinement perfection idealization realization manifestation materialization embodiment incarnation personification representation depiction portrayal characterization dramatization narration storytelling recounting retelling summarizing paraphrasing condensing abridging shortening simplifying clarifying elucidating explaining interpreting analyzing evaluating assessing reviewing critiquing commenting reflecting pondering contemplating meditating praying worshipping venerating adoring reverencing honoring respecting esteeming valuing cherishing treasuring appreciating admiring marveling wondering imagining dreaming envision
How to create schema in MySQLWorkbench
00:07:41To create a schema for the student database, open MySQL Workbench and navigate to your server. Right-click to create a new schema named 'student' by selecting "Create Schema," then apply and close it. Once created, you will see the 'student' database listed without any tables inside.
Create student Entity
00:08:40Creating a Student Entity Class To build a student management application, start by creating an entity class named 'Student' in the package "restAPI.NTT". Define fields for roll number (int), name (String), percentage (float), and branch/specialization (String). Annotate the class with @Entity to mark it as an entity and use @Table(name="student") to specify its corresponding database table. The roll number is set as the primary key using @Id annotation along with @GeneratedValue(strategy=GenerationType.IDENTITY) so that SQL generates unique values automatically.
Configuring Columns and Generating Methods Each field in the Student class should be annotated with @Column; you can optionally provide explicit column names like 'student_name'. Generate getter, setter methods, a default constructor, parameterized constructors excluding auto-generated fields like roll numbers, and override ToString method for better object representation. This setup ensures seamless mapping between Java objects and database tables while maintaining flexibility through customizable annotations.
How to connect springboot application to MySQL database
00:15:52Configuring Spring Boot for MySQL Connection To connect a Spring Boot application to a MySQL database, essential properties must be defined in the 'application.properties' file. These include specifying the JDBC URL (e.g., jdbc:mysql://localhost:3306/student_database), username, and password tailored to your setup. Additionally, setting "hibernate.ddl-auto" as "create" ensures that tables are automatically created or updated based on entity definitions within the schema.
Automatic Table Creation with Hibernate Using annotations like @Entity and @Table in an entity class allows automatic table creation when running the application if configured properly. Setting 'jpa.show-sql=true' enables visibility of SQL queries generated by JPA/Hibernate during runtime. Upon execution, Hibernate checks for existing tables matching entities; it drops them if necessary before creating new ones according to specified parameters.
Create Student Controller
00:23:14The process begins with creating the project and defining an entity. The application is then connected to a MySQL database, automatically generating a table named 'student.' Next, REST endpoints are developed starting with "get student" or "get all students." A new class for the controller is created under the appropriate package name. To designate it as a controller, '@RestController' annotation is added after renaming and refactoring.
How to create Student Repository
00:25:28To create a student repository, start by defining the controller and implementing REST APIs. Begin with an API to fetch all students from the database using HTTP GET requests mapped to '/students'. Use annotations like @GetMapping for URL mapping. Next, set up a repository interface named 'StudentRepository' that extends JpaRepository. Specify the entity class (Student) and its primary key type (Integer). The JpaRepository provides built-in CRUD methods such as findAll(), save(), delete() which can be utilized directly in your application.
Get all students rest end point
00:30:18A GET endpoint is created to fetch all student records from a database using the repository's findAll method. The data, including roll number, percentage, branch, and name of students like ABC (IT) with 98% and XYZ (CU) with 78%, are manually added for testing purposes. To ensure existing tables remain intact during updates without being dropped or recreated unnecessarily, configurations are adjusted before running the Spring Boot application. Once executed successfully on port 8080, Postman can be used to test this endpoint by retrieving all stored student details.
Test Get request in postman
00:34:20A GET request was tested using Postman to retrieve student details from the endpoint localhost:8080/students. Upon sending the request, a successful response with status 200 was received, containing records of two students identified by their roll numbers. This confirmed that the REST API functioned correctly and returned all required data as expected.
what is @PathVariable annotation
00:35:56The @PathVariable annotation is used to dynamically retrieve a specific student's details based on their ID from the URI. A REST endpoint is created with a GET mapping, where the student ID passed in curly brackets within the URL acts as this path variable. The method fetches data using 'findById' from the repository, which returns an optional object; calling '.get()' extracts and assigns it to return only that particular student's information. Testing through Postman confirms functionality by retrieving students’ data accurately when different IDs are provided.
PostMapping to create new student
00:39:50Creating a New Student Entry via Post Mapping To create a new student entry, use the POST request in Postman with the URI 'localhost:8080/student/add'. In the body of this request, pass JSON data containing details like name, percentage, and branch. The roll number is auto-generated upon submission. Using @RequestBody annotation and @PostMapping in Spring Boot ensures that these details are saved into your database table when you hit this endpoint.
Verifying Database Updates After Adding Students After submitting valid student data through POST requests to '/student/add', verify successful creation by checking both API responses (status 200) and querying your database or using GET endpoints for all students. Newly added entries appear immediately with their respective attributes such as roll number generated automatically alongside provided fields like name or branch.
ResponseStatus annotation
00:46:16To indicate a resource has been successfully created, the @ResponseStatus annotation can be used in conjunction with PostMapping. By setting the response status code to 'Created' (201), it replaces the default 'OK' (200) status when a new record is added via POST requests. After saving changes, testing through tools like Postman confirms that newly created entries return a 201 status and are properly recorded.
PutMapping update student details
00:47:40Updating Student Details Using PUT Mapping To update student details, a PUT request is used. For example, if a student's ID is 2 and their percentage needs to be updated from 78 to 92 while changing the name from XYZ to Poonam, this can be achieved by fetching the student record using its ID via 'repo.findById'. After retrieving the data as an object, methods like 'setName' and 'setPercentage' are applied for updates. The modified details are saved back into the database with 'repo.save', ensuring changes reflect both in Postman responses and directly within the database.
PUT vs POST: Differentiating Update From Creation POST mapping creates new records whereas PUT mapping modifies existing ones based on unique identifiers such as IDs or roll numbers. When updating through PUT requests, it’s essential first to fetch current data of that specific identifier before applying modifications. This ensures precise targeting of entries without overwriting unrelated information in storage systems.
DeleteMapping delete student based on id
00:53:35Implementing Delete Functionality in Spring Boot To delete a specific student, the student's ID must be provided. A DELETE mapping is created with a URI that includes the student ID as a path variable. The process involves fetching the student's details using `repo.findById` and then passing this object to `repo.delete`. This ensures accurate deletion of records from both application data and database tables.
Comprehensive CRUD Operations in Spring Boot The project demonstrates creating REST APIs for all CRUD operations: retrieving all students or by roll number (GET), adding new students (POST), updating existing ones (PUT), and deleting them based on their IDs (DELETE). Each operation uses appropriate HTTP methods mapped via annotations like @GetMapping, @PostMapping, etc., ensuring clarity and functionality. With these endpoints implemented successfully, users can now build robust applications handling basic data management tasks efficiently.