[Java] Convert DB code to code value using enum

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.

environment

Overview

The student status code (integer value) registered in the student table is converted to the corresponding code value using enum on the Java side.

ER diagram

image.png

Status code and code value

Status code Code value
1 Student
2 On leave of absence
3 graduate

Package configuration diagram

enum-sample
     |
    src/main/java
     |----jp.co.high_school
     |               |---- app
     |               |     |---- controller
     |               |     |---- response
     |               |
     |               |---- domain
     |               |      |---- service
     |               |      |---- repository
     |               |      |---- model
     |               |  
     |               |---- constant
     |
    src/main/resources
     |----application.yml

Source code

  1. DDL

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';

2. Constant class

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;

        }

}

3. Entity class

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;
	}

}

4. Repository class

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);

}

5. Service class

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;

	}

}


6. Controller class

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);
	}

}

7. Response class

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;

}

Operation check

This time, we will check the operation in the local environment.

Students table

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

image.png

change history

--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.

At the end

If you use enum, it will be much easier to manage master (DB) and constants (Java). I want to use it well.

reference

-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

[Java] Convert DB code to code value using enum
[Android] Convert Android Java code to Kotlin
Convert Java enum enums and JSON to and from Jackson
Sample code to convert List to List <String> in Java Stream
Convert csv file to fixed length record file using enum
How to convert A to a and a to A using AND and OR in Java
Convert Java Powerpoint to XPS
Connect to DB with Java
How to convert Java radix
[Java] Convert ArrayList to array
Convert Map <K, V1> to Map <K, V2> (Convert Map Value)
[Java] Boilerplate code elimination using Lombok
[Java] Convert 1-to-N List to Map
[Java] Boilerplate code elimination using Lombok 2
[Java] Try to implement using generics
Formatting an enum using formatter-maven-plugin (Java)
Sample code using Minio from Java
[Rails] Reflection to db using seeds.rb
[Java] Convert array to ArrayList * Caution
How to use Java enum type
[Android] Convert Map to JSON using GSON in Kotlin and Java
[Java] Express Enum type without using Enum (enumeration) type
Sample code for Singleton implementation using enum
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Convert request parameter to Enum in Spring
Convert all Android apps (Java) to Kotlin
[Java] How to calculate age using LocalDate
Convert from java UTC time to JST time
ERRORCODE = -4471 occurs in Java application using Db2.
[Java] Convert Object type null to String type
Connect from Java to MySQL using Eclipse
Convert SVG files to PNG files in Java
[Java] enum
[Java] Flow from source code to execution
[Rails] How to handle data using enum
Upsert from Java SDK to Azure Cosmos DB
Try using Sourcetrail (win version) in Java code
How to convert a solidity contract to a Java contract class
Try using Sourcetrail (macOS version) in Java code
Using Gradle with VS Code, build Java → run
Write Selenium Java binding code using Silk WebDriver
Convert Java nested beans to aaa.bbb [0] .ccc format
[Java] How to operate List using Stream API
Select * from Java SDK to Azure Cosmos DB
Java code TIPS
Java sample code 02
Java sample code 03
Java sample code 04
[Java] Introduction to Java
Introduction to java
Java sample code 01
Java character code
Launch Docker from Java to convert Office documents to PDF
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
<java> Read Zip file and convert directly to string
[Java] [SQL Server] Connect to local SQL Server 2017 using JDBC for SQL Server
Getting started with Java programs using Visual Studio Code
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Output the maximum value from the array using Java standard output
I tried to operate SQS using AWS Java SDK
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2