JDBC Template을 이용한 반복코드 줄이기
원래 진행했던 많은 양을 템플릿에 담아두고 간편하게 사용하는 것이 가능
Spring 빈을 이용한 코드 간소화
JDBC를 이용한 리스트 목록 만들기
리스트 뽑아내던 긴 내용을 위처럼 간단하게 나타낼 수 있음
JDBC Template을 이용하기 위한 설정
pom.xml
<!-- JDBC Template -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
servlet-context.xml
<beans:bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<beans:property name="username" value="scott"/>
<beans:property name="password" value="tiger"/>
</beans:bean>
<beans:bean name="template" class="org.springframework.jdbc.core.JdbcTemplate">
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
JDBC Template을 이용하기 위한 설정2
예제는 이전에 했던 MVC 게시판 예제의 파일을 이름만 변경해서 사용
설정 1 부분을 모두 한 이후에 아래의 내용 진행
컨트롤러 - 변경된 부분
dao - 변경된 부분
연결 부분
조회하는 부분
이전에 했던 긴 내용을 저렇게 압축
이렇게 더 압축하는 것도 가능
글 작성 부분
만약 위의 쿼리문을 template.query()안의 sql 부분에 넣으면 한줄로도 가능하다.
sql에서 시퀀스 수정
CREATE SEQUENCE "SCOTT"."MVC_BOARD_SEQ" MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 START WITH 1 CACHE 10 NOCYCLE ;
조회수 업데이트 부분
개별 내용 출력 부분
내용 수정 부분
삭제 부분
DAO 총 비교
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
|
public class BDao {
//데이터소스를 쓰지 않고 모두 템플릿으로 처리
// DataSource dataSource;
JdbcTemplate template = null;
public BDao() {
// try {
// Context context = new InitialContext();
// dataSource = (DataSource) context.lookup("java:comp/env/jdbc/oracle");
// } catch (Exception e) {
// e.printStackTrace();
// }
//dao가 생성될 때 템플릿에 값 집어넣어야 오류발생 안함
template = Constant.template;
}
public ArrayList<BDto> list() {
String sql = "select bId, bName, bTitle, bContent, bDate, bHit from mvc_board order by bId desc";
return (ArrayList<BDto>) template.query(sql, new BeanPropertyRowMapper(BDto.class));
// ArrayList<BDto> dtos = new ArrayList<BDto>();
// Connection con = null;
// PreparedStatement pstmt = null;
// ResultSet rs = null;
//
// try {
// con = dataSource.getConnection();
// String sql = "select bId, bName, bTitle, bContent, bDate, bHit from mvc_board order by bId desc";
// pstmt = con.prepareStatement(sql);
// rs = pstmt.executeQuery();
//
// while (rs.next()) {
// int bId = rs.getInt("bId");
// String bName = rs.getString("bName");
// String bTitle = rs.getString("bTitle");
// String bContent = rs.getString("bContent");
// Timestamp bDate = rs.getTimestamp("bDate");
// int bHit = rs.getInt("bHit");
//
// BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
// dtos.add(dto);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(rs != null)rs.close();
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// return dtos;
}
//글 작성하는 메서드
public void write(final String bName, final String bTitle, final String bContent) {
template.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String sql = "insert into mvc_board (bId, bName, bTitle, bContent, bHit) "
+ "values(mvc_board_seq.nextval, ?,?,?,0) ";
PreparedStatement pstmt = null;
pstmt = con.prepareStatement(sql);
pstmt.setString(1, bName);
pstmt.setString(2, bTitle);
pstmt.setString(3, bContent);
return pstmt;
}
});
}
// Connection con = null;
// PreparedStatement pstmt = null;
//
// try {
// con = dataSource.getConnection();
// //글번호는 시퀀스를 생성해서 사용(.nextval하면 자동으로 다음 값이 들어가게 됨)
// String sql = "insert into mvc_board (bId, bName, bTitle, bContent, bHit) values(mvc_board_seq.nextval, ?,?,?,0) ";
// pstmt = con.prepareStatement(sql);
// pstmt.setString(1, bName);
// pstmt.setString(2, bTitle);
// pstmt.setString(3, bContent);
// pstmt.executeUpdate();
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// }
//글번호를 받아서 내용 출력
public BDto content_view(String strID) {
upHit(strID);
String sql = "select bId, bName, bTitle, bContent, bDate, bHit from mvc_board where bId="+strID;
return template.queryForObject(sql, new BeanPropertyRowMapper<BDto>(BDto.class));
}
// BDto dto = null;
// Connection con = null;
// PreparedStatement pstmt = null;
// ResultSet rs = null;
//
// try {
// con = dataSource.getConnection();
// String sql = "select bId, bName, bTitle, bContent, bDate, bHit from mvc_board where bId=?";
// pstmt = con.prepareStatement(sql);
// pstmt.setInt(1, Integer.parseInt(strID));
// rs = pstmt.executeQuery();
//
// if (rs.next()) {
// int bId = rs.getInt("bId");
// String bName = rs.getString("bName");
// String bTitle = rs.getString("bTitle");
// String bContent = rs.getString("bContent");
// Timestamp bDate = rs.getTimestamp("bDate");
// int bHit = rs.getInt("bHit");
//
// dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// if(rs != null)rs.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// return dto;
// }
//조회수 업데이트하는 메서드
private void upHit(final String bId) {
String sql = "update mvc_board set bHit=bHit+1 where bId=?";
template.update(sql,new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, Integer.parseInt(bId));
}
});
}
// Connection con = null;
// PreparedStatement pstmt = null;
//
// try {
// con = dataSource.getConnection();
// String sql = "update mvc_board set bHit=bHit+1 where bId=?";
// pstmt = con.prepareStatement(sql);
// pstmt.setInt(1, Integer.parseInt(bId));
// pstmt.executeUpdate();
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// }
//수정하는 메서드
public void modify(final String bId, final String bName, final String bTitle, final String bContent) {
String sql = "update mvc_board set bName=?, bTitle=?, bContent=? where bId= ?";
template.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, bName);
ps.setString(2, bTitle);
ps.setString(3, bContent);
ps.setInt(4, Integer.parseInt(bId));
}
});
}
// Connection con = null;
// PreparedStatement pstmt = null;
//
// try {
// con = dataSource.getConnection();
// String sql = "update mvc_board set bName=?, bTitle=?, bContent=? where bId= ?";
// pstmt = con.prepareStatement(sql);
//
// pstmt.setString(1, bName);
// pstmt.setString(2, bTitle);
// pstmt.setString(3, bContent);
// pstmt.setInt(4, Integer.parseInt(bId));
//
// pstmt.executeUpdate();
//
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// }
//삭제하는 메서드
public void delete(final String strID) {
String sql = "delete mvc_board where bId= ?";
template.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, Integer.parseInt(strID));
}
});
}
// Connection con = null;
// PreparedStatement pstmt = null;
//
// try {
// con = dataSource.getConnection();
// String sql = "delete mvc_board where bId= ?";
// pstmt = con.prepareStatement(sql);
// pstmt.setInt(1, Integer.parseInt(strID));
// pstmt.executeUpdate();
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// try {
// if(pstmt != null)pstmt.close();
// if(con != null)con.close();
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// }
}
|
cs |
컨스턴트
'학원 > 스프링-학원' 카테고리의 다른 글
mvc_board -> standard 형태로 -마이바티스 수정 (0) | 2022.05.23 |
---|---|
MyBatis (0) | 2022.05.20 |
MVC 로그인 문제 (JDBC 템플릿 사용 부분도 추가) (0) | 2022.05.19 |
MVC_상품정보 관리 문제 (0) | 2022.05.18 |
스프링 MVC 게시판 - 가입, 수정, 삭제 (0) | 2022.05.18 |