스프링부트 JDBC CF서비스 자동연결

1 개요[ | ]

Binding to Data Services with Spring Boot JDBC
스프링부트 JDBC CF서비스 연결
스프링부트 클라우드 데이터소스 JDBC 연결
  • 스프링부트 애플리케이션에서 JDBC로 CF서비스(MySQL, PostgreSQL)에 연결 가능
  • 프로젝트 생성시 Depedencies에서 JDBC 선택
spring-boot-starter-jdbc

2 방법[ | ]

  • Movie 클래스
public class Movie {
	private Integer id;
	private String title;
	private String image;
	private Integer year;
	private String plot;
	
	public Movie(Integer id, String title, String image, Integer year, String plot) {
		this.id = id;
		this.title = title;
		this.image = image;
		this.year = year;
		this.plot = plot;
	}
	
	public String toString() {
		return "Movie [id=" + id + ", title=" + title + ", image=" + image + ", year=" + year + ", plot=" + plot + "]";
	}
}
  • MovieRepository 클래스
@Repository
public class MovieRepository {
	@Autowired NamedParameterJdbcTemplate jdbcTemplate;

	private static final RowMapper<Movie> movieRowMapper = (rs, i) -> {
		Integer id = rs.getInt("id");
		String title = rs.getString("title");
		String image = rs.getString("image");
		Integer year = rs.getInt("year");
		String plot = rs.getString("plot");
		return new Movie(id, title, image, year, plot);
	};
	public List<Movie> findAll() {
		return jdbcTemplate.query("SELECT id, title, image, year, plot FROM movie", movieRowMapper);
	}
	public Movie findOne(Integer id) {
		SqlParameterSource param = new MapSqlParameterSource().addValue("id", id);
		return jdbcTemplate.queryForObject("SELECT id, title, image, year, plot FROM movie WHERE id = :id", param, movieRowMapper);
	}
}
  • MyController 클래스
@RestController
public class MyController {
	@Autowired MovieRepository movieRepository;
		
	@RequestMapping("/")
	public String home() {
		return "Welcome, home!<hr>" + movieRepository.findAll().toString();
	}
}

3 같이 보기[ | ]

4 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}