Student

Saturday, February 1, 2025

 Main

package com.example.quiz1practice;

import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.example.quiz1practice.model.Student;
import com.example.quiz1practice.model.StudentRepository;

@SpringBootApplication
public class Quiz1practiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(Quiz1practiceApplication.class, args);
    }

    @Bean
    ApplicationRunner init(StudentRepository repository){
        return args -> {
            repository.save(new Student("John Doe","johndoe@gmail.com","CSIS"));
            repository.save(new Student("Jane Doe","janedoe@gmail.com","Accounting"));
            repository.findAll().forEach(System.out::println);
        };
    }
}

Model / Student

src/main/java/com/example/crs/model/

package com.example.quiz1practice.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name="student")
public class Student {
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name="name")
    private String name;

    @Column(name="email")
    private String email;

    @Column(name="department")
    private String department;

    public Student() {

    }

    public Student(String name, String email, String department){
        this.name = name;
        this.email = email;
        this.department = department;
    }

    public Integer getId(){
        return id;
    }

    public void setId(Integer id){
        this.id = id;
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getEmail(){
        return email;
    }

    public void setEmail(String email){
        this.email = email;
    }
   
    public String getDepartment(){
        return department;
    }

    public void setDepartment(String department){
        this.department = department;
    }
}

Model / StudentRepository

package com.example.quiz1practice.model;

import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Integer>{
   
}

Controller / StudentController

src/main/java/com/example/[project name]/controller/

package com.example.quiz1practice.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.quiz1practice.model.Student;
import com.example.quiz1practice.model.StudentRepository;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/api")

public class StudentController {
   
    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/students")

    public ResponseEntity<List<Student>> getAllStudents() {
        try {
            List<Student> students = new ArrayList<Student>();
            studentRepository.findAll().forEach(students::add);
           
            if (students.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
   
            return new ResponseEntity<>(students, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
   
    // New method: Get course by ID
    @GetMapping("/students/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable("id") Integer id) {
        Optional<Student> studentData = studentRepository.findById(id);
       
        if (studentData.isPresent()) {
            return new ResponseEntity<>(studentData.get(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    // Create student with validation
    @PostMapping("/students")
    public ResponseEntity<Object> createStudent(@RequestBody Student student) {
    String validationError = validateStudentInput(student);
    if (validationError != null) {
        return ResponseEntity.badRequest().body("{\"error\": \"" + validationError + "\"}");
    }

    try {
        Student _student = studentRepository.save(
            new Student(student.getName(), student.getEmail(), student.getDepartment())
        );
        return new ResponseEntity<>(_student, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

   // Update student with validation
   @PutMapping("/students/{id}")
   public ResponseEntity<Object> updateStudent(@PathVariable("id") Integer id, @RequestBody Student student) {
       Optional<Student> studentData = studentRepository.findById(id);
       
       if (!studentData.isPresent()) {
           return new ResponseEntity<>(HttpStatus.NOT_FOUND);
       }

       String validationError = validateStudentInput(student);
       if (validationError != null) {
           return ResponseEntity.badRequest().body("{\"error\": \"" + validationError + "\"}");
       }

       try {
           Student _student = studentData.get();
           _student.setName(student.getName());
           _student.setEmail(student.getEmail());
           _student.setDepartment(student.getDepartment());
           return new ResponseEntity<>(studentRepository.save(_student), HttpStatus.OK);
       } catch (Exception e) {
           return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
       }
   }

        // 👇 **Place the validateStudentInput method here, at the bottom of the class**
        private String validateStudentInput(Student student) {
            if (student.getName() == null || student.getName().trim().isEmpty()) {
                return "Name cannot be blank or empty.";
            }
           
            if (student.getEmail() == null || !student.getEmail().matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                return "Invalid email format. Please provide a valid email address.";
            }
   
            if (student.getDepartment() == null || student.getDepartment().trim().isEmpty()) {
                return "Department cannot be null or empty.";
            }
   
            return null; // No errors
        }

    // New method: Delete a student
    @DeleteMapping("/students/{id}")
    public ResponseEntity<Integer> deleteStudent(@PathVariable("id") Integer id) {
        try {
            studentRepository.deleteById(id);
            return new ResponseEntity<>(id, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    }
}

Others

src/main/resources/application.properties

spring.application.name=crs

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true

spring.h2.console.path=/h2-console


Init

CtrlShftP > Sprint Initializr > Create Maven > 3.4.1 > Java > com.example >[project name] > Jar > Java version 21 > Spring Web / Spring Data JPa / H2 Database

+ JDK installed

JDBC URL: jdbc:h2:mem:testdb


Postman

Header

Key: Content-Type

Value: Application/JSON


Body

raw

{
    "id": 3,
    "name": "",
    "email": "jamesdoe@gmail.com",
    "department": "Humanities"
}

Flowhouse Manila

Wednesday, July 20, 2016

I went back to Flowhouse Manila again last Sunday with my friend. I was there just about last weekend since we were near it when my girlfriend and I attended a baptism in Cavite.

I was more confident this time without the guiding rope. I could now control moving forward and backward. I had better control also in terms of doing heelside and toeside directions but I had yet to enjoy being in full control.

By the way, there is current promo of the activity this July. If you're a July birthday celebrant, you have 1-hour free ride as long as you bring a paying partner and you could show a valid government ID.

#flowriding #flowrider #flowboarding

To Quietly Weep

Thursday, April 28, 2011

One of the habits I got from using a Mac is constantly moving the mouse cursor to the upper right corner of the screen to hide all opened windows and have the desktop view. I'm using Windows at my office so sometimes I would move the cursor unconsciously on the corner of the screen, only to remember that I'm using a different OS.

Speaking of OS a certain blog teaches you how to fix any computer, be it Windows, Apple or Linux. :D

Wonder About Oranges

Wednesday, April 27, 2011

It's past midnight but I feel the need to write what I learned at this moment.

One of the secrets of being discovered is doing a good work and putting it where people can see it. Obviously, it's about putting it on internet. In it, you just need to wonder at something and invite everyone to wonder with you.

Furthermore if you should wonder. wonder at the things nobody else is wondering about. If everybody’s wondering about apples, go wonder about oranges.

I found the inspiring words above from Austin Kleon.

To Succeed

Tuesday, April 19, 2011

To some, it's all about putting in the time and effort and overcoming fear.

To others, it's about persistence and determination. It's all about pressing on.

Still to several, it's about a couple of things like winning the respect of intelligent people and affection of children, finding the best in others and knowing that one life has breathed easier because you have lived.

A Beautiful Day

Monday, April 18, 2011

Sometimes changing the way you see things can have great results. Sometimes it's all about having the right perspective, as the story below shows.


An old blind man was sitting on a pavement. He had a poster beside him bearing the words "I am blind, please help." In front of him were some coins tossed by people passing by. Time went by and more people walked past him.

Only a handful were giving alms, until a woman came by. She reached out for the poster and began writing. The old blind man touched and felt her dark green heels. Once the woman finished writing, she put back the poster beside the old blind man and walked away.


This time though, more and more people were tossing more and more coins. At the end of the day, the woman with dark green heels came back. The old blind man reached out for the shoes, recognized it and asked the woman. The poster had a saying that goes, "It's a beautiful day, and I can't see it."


An ad video of this is created by the Purple Feather group that specializes on Online Marketing and others.

Seoul Searching 2011

Sunday, April 17, 2011

One of the things I find helpful when planning travels is the availability of information online. Frankly, you won't need a travel agency to do the itinerary for you. This means that you could save some money and you could customize your travel plans.

Last month I had the opportunity to travel to Seoul, South Korea. And here are a couple of things you may need to know.



1. Visa Processing
The Korean Embassy, located at Upper McKinley, Taguig, is closed on Korean Holidays. Take note of any holiday before going there. If you have US, UK, ANZ, or Japan visa, processing is three days. Otherwise it will be five days. For the three-day processing, if you submit on Work Day 1, it will be submitted on Work Day 4.

2. Korean Won reservation
If you have account in BDO, won reservation is three days and you could only reserve in the branch where you opened your account. If you were not able to reserve beforehand, obtain US dollars instead. Although no reservation is needed, you still need to get the funds from your account opening branch. An alternative would be BPI. You could obtain US dollars from any branch.

3. Outlet adapter
Korea has a so-called Schuko style electrical socket so you need a Euro travel plug adapter. Here's how it looks like.

<picture>

4. T Money
T Money card is a re-loadable card used to pay fares around the city. There is a KRW100 discount when used in subways. It can be used in place of credit card as well. When you arrive at the airport, obtain this card from convenience stores such GS25. When used in a bus, you need to swipe when you hop on and exit the vehicle to avoid double charge.

5. Cebu Pacific
The airline only has free 15kg check-in luggage. When your stay in the country is more than 3 days and it would be cold, you may need more than 15 kgs. so anticipate the check-in baggage you will be paying for.

When returning back to Manila, the airline has a very early flight (7:20AM) so that you need to get up early to be on time especially if you're in Seoul and the airport is in Incheon. There is an Airport Limousine which is available as early as 4:20AM (Anguk Station). If you catch this bus, you will be at the airport around 6AM.

6. Places
If I have to rearrange my itinerary, it would be something like the following assuming I am staying around the Anguk area:

9AM Changdeok Palace
1030AM Bukchon Village
1130AM Lunch
1230PM Gyeongbok Palace
* See changing of guard ceremony
* Don traditional Korean dress or hanbok for free
230PM National War Memorial
330PM Namdaemun Market
5PM Seoul Tower
* Check out the locks of love
630PM Cheonggye Stream
* Buy key chain souvenirs near Doota Mall
730PM Dinner at Doota Mall

On the next day, do either a ski tour or DMZ tour. Package tours are arranged by the Cosmojin group.

Note that several palaces are closed either on Mondays or Tuesdays. On Sundays, some establishments are closed as well.

7. Food
Experience Korean culture through food. Try out the following:
Samgyupsal (grilled pork wrapped in a lettuce with bean paste and various kinds of kimchi)
Gamjatang (like pork sinigang)
Bibimbap of various kinds
Jajangmyun (Black bean paste noodles)

8. Accommodation
Contrary to common belief, Seoul actually has a number of affordable good places to stay at. We stayed at Beewon Guesthouse near Anguk station which had heated floors, small fridge, cable tv, bathtub, heated water, free breakfast (bread with jam and yogurt) and so on.

Now with the knowledge mentioned, I am certain that you'd be more productive to get the most out of your visit to the country.