-
10. Query 문을 이용한 Data AccessBack-end Developer/Spring Framework, 설정 및 실습 2018. 12. 31. 15:47
JDBC 사용을 위한 필수 Library 설치 및 설정도 다 했으니, 직접 사용해 봐야겠죠!
혹시나 설정을 아직 안 하셨다면, 9. JDBC 설정 꼭 하고 넘어와주세요.
우리는 데이터를 추가 삭제 등의 처리 및 접근을 위해서 Data 접근 객체가 필요합니다.
다들 많이 들어보신 DAO 입니다. 이왕 정리하는 김에 같이 주로 사용되는 단어도 정리 해볼게요.
DAO / DTO / VO
- DAO (Data Access Object) : 데이터 접근 객체
SQL 문을 통해 데이터 접근 및 조회 등등의 처리를 하는 객체입니다.
Connection을 하나 두고 여러 사용자가 DAO Interface를 사용해 원하는 data로 접근을 유도하는 객체.
DB에 대한 CRUD 처리.
- DTO (Data Transfer Object) : 데이터 전송 객체
data와 해당 객체를 시스템 사이에서 전달해주는 역할을 합니다.여러번의 data(method) 호출을 모아서 DTO를 통해 한번에 처리.- VO (Value Object)
DTO와 같은 개념이지만, read only 속성을 가집니다.값이 같으면 동일한 객체로 보는 성격.Model 객체 생성
오늘은 그중에서도 DAO에 대해 해볼텐데요.
설명과 같이 CRUD Query문도 사용해 볼게요.
일반적으로 자바 언어로 무작정 쓴다고 사용 가능한 것은 아니니까..
어떻게 쓰는지 어떤게 필요한지도 알아 볼게요.
우선 우리가 생성해 둔 테이블이 어떤 구조였는지 파악해봐야 할 것 같아요.
csemall DB에서 'Select * from offer'를 통해 구조를 살펴 보면,
id
name
email
text
1
Alice
alice@snut.ac.kr
스프링 재밋네 ^^
2
Bob
bob@snut.ac.kr
배가고픈 취준생
3
Claire claire@snut.ac.kr
명품이 쵝오야!
이런식으로 구성되어있을거에요.
field가 4항목(id, name, email, text)이 필요하겠네요.
이클립스 실행 하셔서 helloDB 프로젝트 -> csemall package
여기서 'Offer'라는 이름으로 Class 생성 할게요.
거기서 int: id, String: name, email, text 변수 선언 하고, 이에 해당하는 생성자도 만들어주세요.
그리고 생성자 Overloading을 통해 id 항목만 빠진 생성자도 하나 정의할게요.
id는 Auto Increment 항목이 잖아요.
그래서 어떤 기능을 만들 때 굳이 포함이 안될 경우도 있기 때문에 미리 만들었습니다.
그리고 인자가 없는 생성자도 만들고 getter, setter도 만들어주세요.
마지막으로 결과에 대한 출력을 위해 toString 메소드도 생성해주세요.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061package kr.ac.snut.spring.csemall;public class Offer {private int id;private String name;private String email;private String text;public Offer() {}public Offer(int id, String name, String email, String text) {this.id = id;this.name = name;this.email = email;this.text = text;}public Offer(String name, String email, String text) {this.name = name;this.email = email;this.text = text;}public int getId() {return id;}public void setId(int 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 getText() {return text;}public void setText(String text) {this.text = text;}@Overridepublic String toString() {return "Offer [id=" + id + ", name=" + name + ", email=" + email + ", text=" + text + "]";}}cs JDBC Template 생성
Query문을 입력해서 실행 해 줄 template도 생성해 봅시다.
같은 package에서 'OfferDAO'로 Class 생성하세요.
JDBC Template이 필요하니까, 해당 객체를 하나 생성합니다.
이 친구는 DataSource를 입력받아 사용하니까, DI를 이용해 넣어볼게요.
그리고 DataSource에 대한 setter를 생성하고,
DataSource를 외부에서 받아와서 setter를 통해
그 내부에서 JDBC Template을 받아오는 형식으로 구현합니다.
Database에 Query문을 던져 처리하는 메소드도 추가해볼게요.
몇개의 항목이 추가되어있는지 알아보기 위해 이름은 getRowCount라고 명명했습니다.
statment라는 문자열을 선언해 내부에 Query문을 입력하고,
Template 객체의 queryForObject 메소드에 담아 반환합니다.
이 메소드는 객체를 받아와 객체 형태의 타입으로 반환해줍니다. 따라서 Integer class를 넣어줍시다.
123456789101112131415161718192021package kr.ac.snut.spring.csemall;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Component;public class OfferDAO {private JdbcTemplate jdbcTemplateObject;public void setDataSource(DataSource dataSource) {this.jdbcTemplateObject = new JdbcTemplate(dataSource);}public int getRowCount() {String sqlStatement = "SELECT COUNT(*) from offers";return jdbcTemplateObject.queryForObject(sqlStatement, Integer.class);}}cs Bean 등록
OfferDAO를 bean으로 등록해서 실제로 실행이 잘되나 봅시다.
beans.xml -> bean 탭, new bean으로 생성
DI를 통해 데이터도 넘기기로 했죠? 여기서 다시 offerDAO에 property도 추가해주세요.
이렇게 하고 저장하면 beans.xml 코드도 변경됩니다.
12345678910111213141516171819202122<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"><context:property-placeholderlocation="/kr/ac/snut/spring/props/jdbc.properties " /><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="offerDAO" class="kr.ac.snut.spring.csemall.OfferDAO"><property name="dataSource" ref="dataSource"></property></bean></beans>cs 결과 실행
이제 실행 해볼게요.
MainApp Class 생성하고, 여기에 Spring Container를 호출해주세요.
그리고 우리가 사용해야 할 bean 경로를 괄호 내에 넣어주세요.
앗! getRowCount도 실행해봐야 하니까, OfferDAO 객체도 받아와 주세요.
12345678910111213141516package kr.ac.snut.spring.csemall;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp {public static void main(String[] args) {ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("kr/ac/snut/spring/csemall/beans/beans.xml");OfferDAO offerDAO = (OfferDAO) context.getBean("offerDAO");System.out.println("The record count is " + offerDAO.getRowCount());context.close();}}cs 문제없이 실행 잘 되네요.
우리 근데 지난번에 property 말고 '@Autowired'를 이용한 Injection도 실시했었잖아요.
그에 대한것도 다시한번 해볼게요.
Annotation 활용 (@Autowired, @Component)
우선 annotation 기능 활성화 부터 해주세요.
beans.xml -> context 탭, annotation 기능 추가
12345678910111213141516171819202122<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"><context:property-placeholderlocation="/kr/ac/snut/spring/props/jdbc.properties " /><context:annotation-config></context:annotation-config><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="offerDAO" class="kr.ac.snut.spring.csemall.OfferDAO"></bean></beans>cs 이왕 하는김에 '@Component'도 사용해 볼게요.
Component는 Spring이 스캔해서 해당 Class를 자동으로 bean으로 등록해주는 기능을 합니다.
그런데 Spring 입장에선 모든 package를 스캔 할 순없고, 어떤 package인지도 모르죠.
그래서 추가적인 설정이 필요합니다,
beans.xml -> context 탭, Component scan 기능 추가
최종 결과 및 코드
OfferDAO.java
1234567891011121314151617181920212223package kr.ac.snut.spring.csemall;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Component;@Component("offerDAO")public class OfferDAO {private JdbcTemplate jdbcTemplateObject;@Autowiredpublic void setDataSource(DataSource dataSource) {this.jdbcTemplateObject = new JdbcTemplate(dataSource);}public int getRowCount() {String sqlStatement = "SELECT COUNT(*) from offers";return jdbcTemplateObject.queryForObject(sqlStatement, Integer.class);}}cs beans.xml
12345678910111213141516171819202122<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"><context:property-placeholderlocation="/kr/ac/snut/spring/props/jdbc.properties " /><context:annotation-config></context:annotation-config><context:component-scan base-package="kr.ac.snut.spring.csemall"></context:component-scan><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean></beans>cs 결과
Annotation 상당히 편리한 것 같아요. 우선 귀찮아도 기본적인 개념부터 공부해보고,
이후에 제대로 Annotation에 대해 알아보고 쓰면 정말 유용하지 않을까 싶습니다.
반응형'Back-end Developer > Spring Framework, 설정 및 실습' 카테고리의 다른 글
12. Spring MVC framework 설정하기 (0) 2019.01.09 11. Query문을 통한 CRUD 구현 (2) 2019.01.07 9. JDBC 설정 (0) 2018.12.28 8. MySQL workbench 활용. (0) 2018.12.21 7. AOP (Aspect Oriented Programming: 관점 지향 프로그래밍) (0) 2018.12.19