[데이터베이스] 이클립스 SpringBoot로 데이터베이스 사용 Java

목차

  1. 구현한 내용
  2. 코드 구성
  3. 후기

1. 구현한 내용

데이터베이스를 할 때 자주 사용한 university를 데이터들을 사용하였습니다.

이클립스의 SpringBoot를 통해 백엔드 서버에 접속하여 JDBC를 사용하고 데이터베이스의 값을 쿼리문코드를 통해 추출시킵니다.


2. 코드 구성

저는 이클립스 툴을 사용하여 구현하였습니다.

-UnivApplication

-InstructorController : REST API 엔드포인트 정의

-Instructor : 벡엔드에서 다룰 데이터 정의(객체)

-InstructorDAO : JDBC를 이용한 데이터 베이스 접근 메소드 정의

-InstructorService - DAO를 이용해 데이터를 받아오며, 데이터 처리

-aplication.properties : DBMS 접근 정보 저장

 

 

UnivAplication 코드

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UnivApplication {

	static {
    	try {
			Class.forName("org.mariadb.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	public static void main(String[] args) {
		SpringApplication.run(UnivApplication.class, args);
	}
}

 

 

StudentController.java코드

@RestController
@RequestMapping("/api/student")
public class StudentController {

		@Autowired
		private StudentService StudentService;
		
		@GetMapping("/listall") //밑에 있는 함수에다가 맵핑을 시켜놔라 /api/instructor/list를 불러오게됨.
	    public ResponseEntity<?> list() {
	        List<Student> studentor = StudentService.getAllStudent();
	        return ResponseEntity.ok(studentor); //반환받은 데이터를 response로 응답하게된다. //OK는 200을 날려준다.
	    }
		
		@GetMapping("/{id}")
		public ResponseEntity<Student> getStudentById(@PathVariable String id) {
			Student student = StudentService.getStduentById(id);
		    if (student != null) {
		        return ResponseEntity.ok(student);
		    } else {
		        return ResponseEntity.notFound().build();
		    }
		}
		
		@GetMapping("/{id}/takes") //밑에 있는 함수에다가 맵핑을 시켜놔라 /api/instructor/list를 불러오게됨.
	    public ResponseEntity<List<Takes>> getIDStdent(@PathVariable String id){
	        List<Takes> takes = StudentService.getIDStduent(id);
	        return ResponseEntity.ok(takes); //반환받은 데이터를 response로 응답하게된다. //OK는 200을 날려준다.
	    }
}

 

Instructor대신 Student로 코딩

 

Student.java 코드

public class Student {
	private String id;
	private String name;
	private String dept_name;
	private int tot_cred;
	
	public Student(String id, String name, String dept_name, int tot_cred) {
		this.id=id;
		this.name=name;
		this.dept_name=dept_name;
		this.tot_cred = tot_cred;
	}
	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDept_name() {
		return dept_name;
	}
	public void setDept_name(String dept_name) {
		this.dept_name = dept_name;
	}
	public int getTot_cred() {
		return tot_cred;
	}
	public void setTot_cred(int tot_cred) {
		this.tot_cred = tot_cred;
	}
	
}

 

학생 객체를 정의해서 DB에서 데이터를 이 객체로 통해 뽑아낼 수 있습니다.

 

StudentDAO.java 코드

@Repository
public class StudentDAO {
	@Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String dbUser;

    @Value("${spring.datasource.password}")
    private String dbPassword;
    
    public List<Student> getAllStduent() {
        List<Student> studentor = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName("org.mariadb.jdbc.Driver");
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            stmt = conn.createStatement();

            String sql = "SELECT ID, name, dept_name, tot_cred FROM student";
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
            	
            	String id = rs.getString("ID");
                String name = rs.getString("name");
                String dept_name = rs.getString("dept_name");
                int tot_cred = rs.getInt("tot_cred");
                
                Student student = new Student(id,name,dept_name,tot_cred);
                studentor.add(student); //학생 배열에 추가
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return studentor;
    }
    
    public Student getStduentById(String id) {
    	Student student = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;


        try {
            Class.forName("org.mariadb.jdbc.Driver");
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            stmt = conn.createStatement();

            String sql = "SELECT ID, name, dept_name, tot_cred FROM student WHERE id = " + id;
            stmt = conn.createStatement();

            rs = stmt.executeQuery(sql);

            if (rs.next()) {
            	
            	String Id = rs.getString("ID");
                String name = rs.getString("name");
                String dept_name = rs.getString("dept_name");
                int tot_cred = rs.getInt("tot_cred");
                
                student = new Student(Id,name,dept_name,tot_cred);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return student;
    }
    
    public List<Takes> getIDStduent(String id) {
    	 List<Takes> Takes = new ArrayList<>();
         Connection conn = null;
         Statement stmt = null;
         ResultSet rs = null;

         try {
             Class.forName("org.mariadb.jdbc.Driver");
             conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
             stmt = conn.createStatement();

             String sql = "SELECT * FROM takes where id = " + id;
             rs = stmt.executeQuery(sql);

             while (rs.next()) {
             	
             	String Id = rs.getString("ID");
                 String course_id = rs.getString("course_id");
                 String sec_id = rs.getString("sec_id");
                 String semester = rs.getString("semester");
                 int year = rs.getInt("year");
                 String grade = rs.getString("grade");
                 
                 Takes takes = new Takes(Id, course_id, sec_id, semester, year, grade);
                 Takes.add(takes); //takes 배열에 추가
             }

         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 if (rs != null) rs.close();
                 if (stmt != null) stmt.close();
                 if (conn != null) conn.close();
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }

         return Takes;
    }
}

University 데이터베이스에 있는 데이터를 id로 Student객체로 뽑아내는 코드와 Takes의 테이블을 id로 통해 리스트로 뽑아내는 쿼리코드를 볼 수 있습니다.

 

StudentService.java 코드

@Service
public class StudentService {
	@Autowired
	private StudentDAO StudentDAO;
	
	public List<Student> getAllStudent() {
        return StudentDAO.getAllStduent();
    }
	
	public Student getStduentById(String id) {
		return StudentDAO.getStduentById(id);
	}

	public List<Takes> getIDStduent(String id) {
		// TODO Auto-generated method stub
		return StudentDAO.getIDStduent(id);
	}
}

DAO에 코드를 실행시키도록 하는 Service 코드입니다.

 

다른 프로젝트의 Main코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static void main(String[] args) {
        try {
            //String apiUrl = "http://localhost:8080/api/instructor/list"; // REST API 엔드포인트 URL
            String apiUrl = "http://localhost:8080/api/student/00128/takes"; // REST API 엔드포인트 URL
            //String apiUrl = "http://localhost:8080/api/student/listall"; // REST API 엔드포인트 URL
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");

            if (connection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            String output;
            StringBuilder response = new StringBuilder();
            
            while ((output = br.readLine()) != null) {
                response.append(output);
            }
            connection.disconnect();

            System.out.println("Response from the server:");
            //System.out.println(response.toString());
           
            /*출력문이 너무 어렵습니다... 객체에도 toString을 오버라이딩시켜서 출력방식을 바꾸게 해도 넘어와서 객체가 바뀐건지 잘 모르겟어서
            비효율적인 방식밖에 없었습니다.*/
            //첫번째 방법
            String replaceString = response.toString().replaceAll("\""," "); //특수문자 " 제거
            replaceString = replaceString.replace("},{","\n"); //가운데에 },{를 기준으로 들여쓰기
            replaceString = replaceString.replaceAll("}" , ""); // 특수문자 } 제거
            replaceString = replaceString.replace("{" , ""); //특수문자 { 제거
            replaceString = replaceString.replace("[" , ""); //특수문자 [ 제거
            replaceString = replaceString.replace("]" , ""); //특수문자 ] 제거
            replaceString = replaceString.replace("," , "|"); //특수문자 , 를 |로 변경
            System.out.println(replaceString); //출력

            
            
            
            /////////////////////////////////////////////////////////////////////////////////
            // 두번째 방법이지만 효율성이 위보다 더욱 떨어져서 주석처리하였습니다.
            
            
            /*String replaceString = response.toString().replaceAll("\""," ");
            //특수문자들 제거 }의 경우 내려쓰기로 변경
            replaceString = replaceString.replace("[", "");
            replaceString = replaceString.replace("]", "");
            replaceString = replaceString.replace("{", "");
            replaceString = replaceString.replace("}", "\n");
            replaceString = replaceString.replace(",", " ");
            replaceString = replaceString.replace(":", " ");
            //course_id, Sec_id, year, id, grade, semester 들 모두 제거
            replaceString = replaceString.replace("course_id", "");
            replaceString = replaceString.replace("sec_id", "");
            replaceString = replaceString.replace("year", "");
            replaceString = replaceString.replace("grade", "");
            replaceString = replaceString.replace("id", "");
            replaceString = replaceString.replace("semester", "");
            
            System.out.println("  Course_id | sec_id | year | grade |  id  | semester");
            System.out.println(replaceString);*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

출력결과

 

밑쪽에 코드는 위 출력을 예쁘게 하려던 코드인데 한줄로 출력되는 결과를 가지런히 보이기 위한 코드입니다. 이부분은 Gson으로 하시면 아마 저보다 훨~씬 예쁘게 출력 할 수 있을겁니다.

 

이상으로 벡엔드 서버에 apiurl 과 같이 접속시켜서 위에 DAO Service Ccontroller등 코드를 통해 원하는 데이터를 출력시킨 과제였습니다.