This is a sample that converts the status code registered in the DB into a code value on the Java side. This eliminates the need to create a master that defines the meaning of the status code. The framework is Spring Boot.
The student status code (integer value) registered in the student table is converted to the corresponding code value using enum on the Java side.
Status code | Code value |
---|---|
1 | Student |
2 | On leave of absence |
3 | graduate |
enum-sample
|
src/main/java
|----jp.co.high_school
| |---- app
| | |---- controller
| | |---- response
| |
| |---- domain
| | |---- service
| | |---- repository
| | |---- model
| |
| |---- constant
|
src/main/resources
|----application.yml
Student table
CREATE TABLE `students` (
`student_id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT 'Student ID',
`student_name` varchar(300) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Student name',
`sex` tinyint(4) DEFAULT NULL COMMENT 'sex',
`school_year` tinyint(4) DEFAULT NULL COMMENT 'School year',
`class` tinyint(4) DEFAULT NULL COMMENT 'class',
`student_status` tinyint(4) DEFAULT NULL COMMENT 'Student status',
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='student';
Define and use enums in constant classes. You can create an enum as a class, but I defined it in the class assuming that the number will be large. By doing this, you can manage multiple enums with one class file.
Constant.java
package jp.co.high_school.constant;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.Getter;
/**
*Constant class
* @author CHI-3
* @Version 1.0
*/
public class Constant {
/**
* StudentStatus
*Student status
*/
@Getter
public static enum StudentStatus {
In(1, "Student"),
Rest(2, "On leave of absence"),
Out(3, "graduate");
private StudentStatus(int key, String value) {
this.key = key;
this.value = value;
}
private int key;
private String value;
//Returns all code values
public static Stream<StudentStatus> stream(){
return Stream.of(StudentStatus.values());
}
//Returns a code value that matches the retrieved code
public static String getStatusValue(Byte code) {
return Stream.of(StudentStatus.values()).filter(v -> v.getKey() == code).map(v -> v.getValue()).collect(Collectors.joining());
}
}
//Not used this time: Described as proof that multiple enums can be defined in one class
/**
* Grade
*Grades
*/
@Getter
public static enum Grade{
//Excellent, good, acceptable are the minimum requirements-sam, not possible is the best condition
Excellent(1, "Yu", 90),
Good(2, "Good", 75),
Passing(3, "Yes", 60),
Failing(4, "Impossible", 59);
private Grade(int key, String value, int order) {
this.key = key;
this.value = value;
this.order = order;
}
private int key;
private String value;
private int order;
}
}
This time, it was automatically generated from DB using Hibernate Tools of Eclipse.
Student.java
package jp.co.high_school.domain.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the students database table.
*
*/
@Entity
@Table(name="students")
@NamedQuery(name="Student.findAll", query="SELECT s FROM Student s")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="student_id")
private Integer studentId;
@Column(name="class")
private Byte class_;
@Column(name="school_year")
private Byte schoolYear;
private Byte sex;
@Column(name="student_name")
private String studentName;
@Column(name="student_status")
private Byte studentStatus;
//bi-directional one-to-one association to Grade
@OneToOne(mappedBy="student")
private Grade grade;
public Student() {
}
public Integer getStudentId() {
return this.studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Byte getClass_() {
return this.class_;
}
public void setClass_(Byte class_) {
this.class_ = class_;
}
public Byte getSchoolYear() {
return this.schoolYear;
}
public void setSchoolYear(Byte schoolYear) {
this.schoolYear = schoolYear;
}
public Byte getSex() {
return this.sex;
}
public void setSex(Byte sex) {
this.sex = sex;
}
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Byte getStudentStatus() {
return this.studentStatus;
}
public void setStudentStatus(Byte studentStatus) {
this.studentStatus = studentStatus;
}
public Grade getGrade() {
return this.grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
}
By specifying the student ID, the information of the corresponding student is acquired.
StudentRepository.java
package jp.co.high_school.domain.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import jp.co.test_shop.domain.model.Student;
/**
*Student's repository class for table operations
* @author CHI-3
* @Version 1.0
*/
@Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{
/**
*findByStudentId method
*Get the student corresponding to the student ID
* @param studentId
* @return student
*/
public Student findByStudentId(Integer studentId);
}
Converts the student status code of the acquired student to the corresponding status code and returns it.
StudentInformationService.java
package jp.co.high_school.domain.service;
import java.util.Optional;
import org.springframework.stereotype.Service;
import jp.co.test_shop.constant.Constant.StudentStatus;
import jp.co.test_shop.domain.model.Student;
import jp.co.test_shop.domain.repository.StudentRepository;
import lombok.RequiredArgsConstructor;
/**
*Service class for acquiring student information
* @author CHI-3
* @version 1.0
*/
@Service
@RequiredArgsConstructor
public class StudentInformationService {
private final StudentRepository studentRepository;
/**
*getStatus method
*Get the student status (code value) of the target student
* @param studentId Student ID
* @return Student status (code value)
*/
public String getStatus(Integer studentId) throws Exception{
Student student = studentRepository.findByStudentId(studentId);
//Raise an exception if there is no student associated with the student ID
Optional.ofNullable(student).orElseThrow(Exception::new);
String status = null;
/*Status code → Corresponding code value: Comment out due to change to description by stream
for(StudentStatus ss:StudentStatus.values()){
if(ss.getKey() == student.getStudentStatus()) {
status = ss.getValue();
break;
}
}
*/
//Status code → Corresponding code value
status = StudentStatus.getStatusValue(student.getStudentStatus());
return status;
}
}
Formats and returns the code value obtained by the Service class.
StudentInformationController.java
package jp.co.high_school.app.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import jp.co.test_shop.app.response.StudentStatusResponse;
import jp.co.test_shop.domain.service.StudentInformationService;
import lombok.RequiredArgsConstructor;
/**
*Controller class for acquiring student information
* @author CHI-3
* @Version 1.0
*/
@RestController
@RequiredArgsConstructor
public class StudentInformationController {
private final StudentInformationService studenInformationService;
/**
*getStatus method
*Get student status
* @param studentId Student ID
* @return Response entity (status code value + HTTP status)
*/
@GetMapping("/student-information/{studentId}")
public ResponseEntity<StudentStatusResponse> getStatus(@PathVariable("studentId") Integer studentId){
String status = studenInformationService.getStatus(studentId);
StudentStatusResponse studentStatusReponse = StudentStatusResponse.builder().status(status).build();
return new ResponseEntity<>(studentStatusReponse, HttpStatus.OK);
}
}
StudentStatusResponse.java
package jp.co.high_school.app.response;
import lombok.Builder;
import lombok.Getter;
/**
*Student status response class
*Used for molding student status
* @author CHI-3
* @Version 1.0
*/
@Getter
@Builder
public class StudentStatusResponse {
private String status;
}
This time, we will check the operation in the local environment.
student_id | student_name | sex | school_year | class | student_status |
---|---|---|---|---|---|
1 | Student | 1 | 1 | 2 | 1 |
If the student table has the above contents, hitting the API (using Advanced Rest Client) will return the following result. The code value (while attending school) corresponding to the status code (1) is properly taken.
Method | GET |
---|---|
URL | http://localhost:8080/student-information/1 |
--2020/07/13: Status code → Change the description of the process to acquire the corresponding code value and the package configuration of the constant class.
If you use enum, it will be much easier to manage master (DB) and constants (Java). I want to use it well.
-How to use Java enum you don't know | SE channel -Basic usage of enum (enum) and code example | Qiita -How to use enums in Java | Narikiri Architect --Java 8 --Filtering Map Samples | codeflow
Recommended Posts