본문 바로가기
Web/Spring

Spring MVC Board(2)_Spring JDBC

by 미티치 2016. 5. 19.

■ Spring JDBC 개요

 

 

Spring JDBC : JDBC가 가지고 있는 문제점을 해결하기 위해 JDBC를 한 단계 더 추상화시켜서 새로운 JDBC API를 제공

 

이전에는 DAO에서 무수히 많은 중복 코드가 발생하였었다. Connection 생성, PrepareStatement 생성, SQLException 처리와 같이 중복적으로 구현해야하는 소스가 너무 많았다. 따라서 하나의 SQL문을 만들기위해 StringBuffer를 사용하는 과정이 상당히 비효율적이었다. 그렇다면 SQL문을 메소드 내에 구현할 필요 없이 상수처럼 사용하게 된다면?

 

Spring 프레임워크는 기존의 JDBC를 이용하여 Persistence 계층을 구현할 때 발생하는 문제점을 해결하기 위해 JDBC를 추상화한 API를 새롭게 제공했다. Spring JDBC는 Connection 생성, PrepareStatement 생성, SQLException 처리와 같은, 지금까지 개발자들이 직접 구현해야 했었던 반복적인 작업들을 Spring JDBC 내에서 처리하도록 함으로써 개발 속도의 향상 뿐만 아니라 개발자들의 잘못된 구현으로 인해 발생했던 많은 문제점들을 해결할 수 있게되었다.

 

정리하자면 Spring JDBC를 이용하면 Connection관리, Statement 관리, Result 관리파라미터 setting, 트랜잭션 관리를 Spring JDBC에서 해주기 때문에 개발자는 SQL문, Row 데이터 추출, 파라미터 선언만 신경쓰면 된다.

 

 

 

 

 

■ Spring JDBC Template 환경 설정

 

 

Maven의 기본사양에 MyBatis는 있지만 Oracle은 없기 때문에

dependency는 내가 쓸려고 maven에 던져주는거고 근데 이걸 해도 maven은 oracle이 기본적으로 없기 때문에 ojdbc6.jar파일을 직접 실제경로에 집어넣어줬다.

하지만

 

 

1. Spring MVC Project 생성하여 pom.xml의 <dependencies></dependencies> 안에 다음과 같은 코드를 추가한다

: 이렇게 직접 dependency 해주는 부분은 '이 프로젝트에서 spring-jdbc와 oracle jdbc 라이브러리들을 쓸거야'라고 Maven에 알려주는 동작이다. 하지만 이렇게 알려줘도 Maven은 Oracle을 알지 못한다. Maven은 MyBatis는 알지만 Oracle은 뭔지 모른다.  (아는게 더 이상한것같다..) 프로젝트를 동작시켜보면 C:User/어쩌고저쩌고 위치에 ojdbc6어쩌고 저쩌고 파일이 없습니다 라고 에러가 뜬다. 이 에러가 바로 Maven이 Oracle을 모르기때문에 dependency로 '나 이거 쓸거야!'라고 해도 Maven은 '없는데?'라고 하기 때문이다. 따라서 직접 사용자가 이 에러가 뜬 경로에 ojdbc6.jar 파일을 ojdbc6어쩌고저쩌고 파일로 이름만 바꾸어서 넣어줘야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- JDBC Template -->
  <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>4.1.4.RELEASE</version>
  </dependency>
        
   <!-- JDBC설정 -->
  <dependency>   
       <groupId>com.oracle</groupId>
       <artifactId>ojdbc6</artifactId>
       <version>11.2.0.3</version>
  </dependency>  
cs

 

    

 

2servlet-context.xml 파일에 다음과 같은 코드를 추가한다.

  : beans에 JdbcTemplate빈즈 생성, dataSource를 멤버변수로 갖고 있는 template을 등록한다.

  -> servlet-context.xml에 생성하는 빈즈는 자동으로 등록되기 때문에 바로 사용가능하지만, 내가 따로 xml파일을만들어서 그 안에 빈즈를 생성하면 web.xml에 내가 만든 xml파일을 매핑시켜서 쓰면 된다.

1
2
3
4
5
6
7
8
9
10
    <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="hr" />
        <beans:property name="password" value="orcl" />
    </beans:bean>
    
    <beans:bean name="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>
cs

 

 

 

 

3. Controller에 JdbcTemplate 변수 추가하고, setJdbcTemplate( ) 추가

 : Autowired 어노테이션은 Controller에 진입하면 두 객체 사이의 의존 관계를 자동으로 해주는 어노테이션이다. bean 등록 후 Autowired 어노테이션을 추가해야 JdbcTemplate를 사용할 수 있다. 이전까지는 보통 Bean을 컨트롤러에서 구현하여 사용하는데, JdbcTemplate는 Spring에서 구현하고 있기 때문에(아래 추가 설명) xml에서 콜하고 Controller에서 set해서 DAO단에서 사용하면 된다.

 -> 예를들면 Model이랑 Request도 하나의 빈인데 얘네는 스프링이 다 알고있는 애들이니까 그냥 선언해서 바로 쓸 수있고

     JDBCTemplate도 하나의 빈인데 얘는 스프링이 모르니까 servlet-context에서 Usebean만해주면 스프링이 알아서해준다.

     여기서 알아서 만들어주는 과정이 @Autowired. 아래 코드를보면 매개변수로 JdbcTemplate template을 받고 있다.

     이 파라미터를 누가 던져줘야 이 메소드에서 받을 수 있으니까, 이 파라미터를 던져주는 게 바로 spring이다. (자동으로)

1
2
3
4
5
6
7
public JdbcTemplate template;
 
 @Autowired
 public void setTemplate(JdbcTemplate template) {
  this.template = template;
  Constant.template = this.template;
 }
cs

 


 

 

4. Constant 객체를 생성해서 Template

 : 생성한 template을 public static으로 선언해서 어디서든 contant객체를 이용해 사용을 쉽게 하기 위해 util 패키지를 생성해서 다음과 같은 Constant 객체를 생성한다.

 

1
2
3
4
5
6
7
8
package com.java.spring_MVC_Test.util;
 
import org.springframework.jdbc.core.JdbcTemplate;
 
public class Constant {
 
    public static JdbcTemplate template;
}
cs

 

 

 

 

 

 

 

■ Spring JDBC Template 예제

 

 <=    패키지 구조

 


[ HomeController.java ]

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
package com.java.spring_MVC_Test;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
    
}
 
cs



[ BCommand.java ]

1
2
3
4
5
6
7
8
9
10
package com.java.spring_MVC_Test.Command;
 
import org.springframework.ui.Model;
 
//각 Command를 동적바인딩하기 위한 인터페이스
public interface BCommand {
    
    void execute(Model model);
    
}
cs


[ BContentCommand.java ]
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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
import com.java.spring_MVC_Test.dto.BDto;
 
// 게시글 목록에서 글 클릭하면 해당 글을 보여주는 작업
public class BContentCommand implements BCommand {
    
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
 
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String bId = request.getParameter("bId");
        BDao dao = new BDao();
        BDto dto = dao.contentView(bId);
        
        model.addAttribute("content_view", dto);
        
    }
 
}
 
cs


[ BDeleteCommand.java ]

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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
 
//게시글 삭제 
public class BDeleteCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
        
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        
        String bId = request.getParameter("bId");
        BDao dao = new BDao();
        dao.delete(bId);
        
    }
}
 
cs



[ BListCommand.java ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.java.spring_MVC_Test.Command;
 
import java.util.ArrayList;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
import com.java.spring_MVC_Test.dto.BDto;
 
//게시글 전체 리스트 가지고 옴
public class BListCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
        
        BDao dao = new BDao();
        ArrayList<BDto> dtos = dao.list();
        System.out.println(dtos);
        model.addAttribute("list", dtos);
        
    }
}
cs


[ BModifyCommand.java ]
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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
 
//게시글 수정
public class BModifyCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
 
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        
        BDao  dao = new BDao();
        dao.modify(bId, bName, bTitle, bContent);
            
    }
}
cs


[ BReplyCommand.java ]
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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
 
//게시글에서 답글 버튼 클릭하면 답글다는 페이지로 이동 -> 게시글정보 가지고 이동
public class BReplyCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
 
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        
        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        String bGroup = request.getParameter("bGroup");
        String bStep = request.getParameter("bStep");
        String bIndent = request.getParameter("bIndent");
        
        BDao dao = new BDao();
        dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);
        
    }
}
cs



[ BReplyViewCommand.java ]

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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
import com.java.spring_MVC_Test.dto.BDto;
 
public class BReplyViewCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String bId = request.getParameter("bId");
        
        BDao dao = new BDao();
        BDto dto = dao.reply_view(bId);
        
        model.addAttribute("reply_view", dto);
        
    }
}
 
cs


[ BWriteCommand.java ]
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
package com.java.spring_MVC_Test.Command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.java.spring_MVC_Test.dao.BDao;
 
 
public class BWriteCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
        
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        
        BDao dao = new BDao();
        dao.write(bName, bTitle, bContent);
    }
}
cs


[ BContoller.java ]
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
package com.java.spring_MVC_Test.Controller;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import com.java.spring_MVC_Test.Command.BCommand;
import com.java.spring_MVC_Test.Command.BContentCommand;
import com.java.spring_MVC_Test.Command.BDeleteCommand;
import com.java.spring_MVC_Test.Command.BListCommand;
import com.java.spring_MVC_Test.Command.BModifyCommand;
import com.java.spring_MVC_Test.Command.BReplyCommand;
import com.java.spring_MVC_Test.Command.BReplyViewCommand;
import com.java.spring_MVC_Test.Command.BWriteCommand;
import com.java.spring_MVC_Test.util.Constant;
 
/**
 * Servlet implementation class BoardFrontController
 */
@Controller
public class BController {
 
    BCommand command = null;
    
    public JdbcTemplate template;
    
    @Autowired
    public void setTemplate(JdbcTemplate template) {
        this.template = template;
        Constant.template = this.template;
    }
    
    //게시판 글 리스트 보여주기
    @RequestMapping("/list")
    public String list(Model model) {
        System.out.println("list()");
        command = new BListCommand();
        command.execute(model);
        
        return "list";
    }
    
    //게시판에 글 쓰는 페이지 보여주기
    @RequestMapping("/write_view")
    public String write_view(Model model) {
        System.out.println("write_view()");
        
        return "write_view";
    }
    
    //게시판에 글 쓰는 동작
    @RequestMapping("/write")
    public String write(HttpServletRequest request, Model model) {
        System.out.println("write()");
        
        model.addAttribute("request", request);
        command = new BWriteCommand();
        command.execute(model);
        
        return "redirect:list";
    }
    
    //게시글 목록에서 글 클릭하면 게시글을 보여주기
    @RequestMapping("/content_view")
    public String content_view(HttpServletRequest request, Model model){
        System.out.println("content_view()");
        model.addAttribute("request", request);
        command = new BContentCommand();
        command.execute(model);
        
        return "content_view";
    }
    
    //게시글 수정 버튼 누르면 동작
    @RequestMapping(value="/modify", method=RequestMethod.POST )
    public String modify(HttpServletRequest request, Model model){
        System.out.println("modify()");
        
        model.addAttribute("request", request);
        command = new BModifyCommand();
        command.execute(model);
        
        return "redirect:list";
    }
    
    //답글 달기 버튼 클릭하면 보여주는 답글 보여주는 페이지
    @RequestMapping("/reply_view")
    public String reply_view(HttpServletRequest request, Model model){
        System.out.println("reply_view()");
        
        model.addAttribute("request", request);
        command = new BReplyViewCommand();
        command.execute(model);
        
        return "reply_view";
    }
    
    //답글 달아주는 
    @RequestMapping("/reply")
    public String reply(HttpServletRequest request, Model model) {
        System.out.println("reply()");
        
        model.addAttribute("request", request);        
        command = new BReplyCommand();
        command.execute(model);
        
        return "redirect:list";
    }
    
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request, Model model) {
        System.out.println("delete()");
        
        model.addAttribute("request", request);
        command = new BDeleteCommand();
        command.execute(model);
        
        return "redirect:list";
    }
}
 
cs


[ BDao.java ]
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
package com.java.spring_MVC_Test.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
 
import javax.sql.DataSource;
 
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
 
import com.java.spring_MVC_Test.dto.BDto;
import com.java.spring_MVC_Test.util.Constant;
 
public class BDao {
 
    DataSource dataSource;
    JdbcTemplate template = null;
    
    public BDao() {
        template = Constant.template;
    }
    
    // 게시글 가지고 오는 메소드
    public ArrayList<BDto> list() {
        String query = "select bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from mvc_board order by bGroup desc, bStep asc";
        System.out.println("return : "+(ArrayList<BDto>)template.query(query, new BeanPropertyRowMapper<BDto>(BDto.class)));
        return (ArrayList<BDto>)template.query(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
    
    // 글 쓰는 메소드
    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 query = "insert into mvc_board (bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, 0, mvc_board_seq.currval, 0, 0 )";
                PreparedStatement pstmt = con.prepareStatement(query);
                pstmt.setString(1, bName);
                pstmt.setString(1, bTitle);
                pstmt.setString(2, bContent);
                
                return pstmt;
            }
        });
    }
 
    // 글 보여주는 메소드
    public BDto contentView(String bId) {
        String query = "select * from mvc_board where bId =" + bId;
        upHit(bId);
        return template.queryForObject(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
    
    // 게시글 삭제 
    public void delete(final String bId) {
        String query = "delete from mvc_board where bId = ?";
        template.update(query, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1, Integer.parseInt(bId));
            }
        });
    }
    
    // 게시글 수정
    public void modify(final String bId, final String bName, final String bTitle, final String bContent) {
        String query="update mvc_board set bName = ?, bTitle = ?, bContent = ? where bId = ?";
        template.update(query, 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));
            }
        });
    }
    
    // 답글 쓰는 페이지
    public BDto reply_view(String str) {
        String query ="select * from mvc_board where bId ="+str;
        return template.queryForObject(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
    
    // 답글 다는 메소드
    public void reply(final String bId, final String bName, final String bTitle, final String bContent, final String bGroup, final String bStep, final String bIndent) {        
        
        template.update(new PreparedStatementCreator() {
            
            @Override
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                replyShape(bGroup, bStep);
                String query = "insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) "
                        + "values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)";
                PreparedStatement pstmt = con.prepareStatement(query);
                pstmt.setString(1, bName);
                pstmt.setString(2, bTitle);
                pstmt.setString(3, bContent);
                pstmt.setInt(4, Integer.parseInt(bGroup));
                pstmt.setInt(5, Integer.parseInt(bStep) + 1);
                pstmt.setInt(6, Integer.parseInt(bIndent) + 1);
                
                return pstmt;
            }
        });
    }
 
    // 답글을 달았을 때 bStep+1 해주는 메소드 
    private void replyShape( final String bGroup, final String bStep) {
        String query="update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
        template.update(query, new PreparedStatementSetter(){
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1, bGroup);
                ps.setString(2, bStep);
            }
        });
    }
    
    //조회 수 +1 
    private void upHit(final String bId) {
        String query = "update mvc_board set bHit = bHit + 1 where bId = ?";
        template.update(query, new PreparedStatementSetter(){
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1, Integer.parseInt(bId));
            }
        });
    }
    
}
 
cs


[ BDto.java ]
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
package com.java.spring_MVC_Test.dto;
 
import java.sql.Timestamp;
 
public class BDto {
 
    int bId; // 고유번호 아마 프라이머리키
    String bName; // 작성자명
    String bTitle; // 제목
    String bContent; // 내용
    Timestamp bDate; // 날짜
    int bHit; // 조회수
    int bGroup; // 답글과 글은 같은 그룹번호를 공유함 (오더바이의 기준)
    /*
    답글 또한 하나의 리스트이고 그 리스트의 번호 관리하는거
    답글은 맨 뒤에만 글 쓸 수 있는 기본리스트와 달리 중간에도 글 쓰기가 가능하기 때문에 
    중간에 글 쓸 경우 그 중간을 기준으로 게시판 번호를 +1씩한다 이 bStep이 그 +1할 친구
    */
    int bStep;      // 답글의 번호
    int bIndent; // 답글의 답글인지 답글의 답글의 답글인지 볼 수 있는 들여쓰기 정도
    public BDto() {
        // TODO Auto-generated constructor stub
    }
    
    public BDto(int bId, String bName, String bTitle, String bContent, Timestamp bDate, int bHit, int bGroup, int bStep, int bIndent) {
        // TODO Auto-generated constructor stub
        this.bId = bId;
        this.bName = bName;
        this.bTitle = bTitle;
        this.bContent = bContent;
        this.bDate = bDate;
        this.bHit = bHit;
        this.bGroup = bGroup;
        this.bStep = bStep;
        this.bIndent = bIndent;
    }
 
    public int getbId() {
        return bId;
    }
 
    public void setbId(int bId) {
        this.bId = bId;
    }
 
    public String getbName() {
        return bName;
    }
 
    public void setbName(String bName) {
        this.bName = bName;
    }
 
    public String getbTitle() {
        return bTitle;
    }
 
    public void setbTitle(String bTitle) {
        this.bTitle = bTitle;
    }
 
    public String getbContent() {
        return bContent;
    }
 
    public void setbContent(String bContent) {
        this.bContent = bContent;
    }
 
    public Timestamp getbDate() {
        return bDate;
    }
 
    public void setbDate(Timestamp bDate) {
        this.bDate = bDate;
    }
 
    public int getbHit() {
        return bHit;
    }
 
    public void setbHit(int bHit) {
        this.bHit = bHit;
    }
 
    public int getbGroup() {
        return bGroup;
    }
 
    public void setbGroup(int bGroup) {
        this.bGroup = bGroup;
    }
 
    public int getbStep() {
        return bStep;
    }
 
    public void setbStep(int bStep) {
        this.bStep = bStep;
    }
 
    public int getbIndent() {
        return bIndent;
    }
 
    public void setbIndent(int bIndent) {
        this.bIndent = bIndent;
    }
    
}
 
cs


[ Constant.java ]

 

1
2
3
4
5
6
7
8
package com.java.spring_MVC_Test.util;
 
import org.springframework.jdbc.core.JdbcTemplate;
 
public class Constant {
 
    public static JdbcTemplate template;
}
cs

 

 

 

 Tip & Tech


- BDao에서 매개변수를 final로 선언한 이유는?

 : 값이 넘어오는 과정에서 값이 변할수도 있기 때문에 매개변수를 다 final로 선언


- query와 queryForObject의 차이점?

 :  BDao를 보면 리턴형이 template.query 또는 template.queryForObject가 있는데, 이 둘의 차이점은 query는 리턴형이 List형이고 queryForObject는 리턴형이 말 그대로 Object 이다.



'Web > Spring' 카테고리의 다른 글

Spring MVC Board(3)_MyBatis  (0) 2016.05.20
Spring MVC Board (1)_Spring Board  (0) 2016.05.19
Spring MVC(3)_Annotation & @RequestMapping  (0) 2016.05.17
Spring MVC(2)  (0) 2016.05.16
Spring MVC(1)  (0) 2016.05.16