Java/Spring framwork

(Spring) Spring JDBC를 이용한 DataBase SELECT 데이터 받기

휘휘o 2020. 9. 15. 16:12

객체가 DTO 형식일 경우 

RowMapper<DTO> rowMapper = BeanPropertyRowMapper.newInstance(DTO.class);
	

DTO클래스를 rowmapper로 만들어서 DataMappingClass 파라미터를 넘겨줘야한다.

 

1. 객체 형식

 

jdbc.queryForObject(SQL, Parameter, DataMappingClass)를 사용한다.

 

int, double로 넘겨받고 싶다면 DataMappingClass에 해당하는 클래스를 넣으면 된다. (Integer.class, Double.clas)

 

public CommentImage selectCommentImage(int commentImageId) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		
		params.addValue("id", commentImageId);
		
		return jdbc.queryForObject(SELECT_COMMENT_IMAGE, params, rowMapperCommentImage);
	}
public double countDisplayScore(Integer displayInfoId) {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("id", displayInfoId);

		return jdbc.queryForObject(SELECT_AVERAGE_DISPLAY, params, Double.class);
	}

 

 

2. 리스트 객체 형식

 

queryForList() 와 query()를 사용할 수 있다.

 

데이터를 받아오기위한 표준형식은 query()다. 다른 메서드들과 차이점은 결과 리스트들을 받아 오기 위해서 Row 매퍼를 이용해야만 받아올 수 있다.

 

queryForList()은 RowMapper를 구현하지 않고 심플하게 리스트를 받아올 수 있다.

 

query()는 RowMapper를 구현해서 리스트를 받아와야한다.

 

둘의 차이점 : stackoverflow.com/questions/1660756/java-programming-spring-and-jdbctemplate-use-query-queryforlist-or-queryfor

public int selectCount(Integer categoryId) {
		MapSqlParameterSource params = new MapSqlParameterSource();

		params.addValue("id", SetId(categoryId));
		List<Integer> list = jdbc.queryForList(SELECT_COUNT_PRODUCT, params, Integer.class);
		int sum = 0;
		for(int i: list)sum += i;
		return sum;
	}

 

	public List<CommentImage> selectCommentImages(Integer commentId){
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("id", commentId);

		return jdbc.query(SELECT_COMMENT_IMAGE, params, rowMapperCommentImages);
	}