SpringBoot는 스프링 애플리케이션의 생성, 운영, 디버깅 및 배포를 단순화하기 위해 태어난 제품입니다. 자동 어셈블리 기능을 통해 외부 XML 구성보다는 비즈니스 자체에 더 집중할 수 있습니다. 웹 프로젝트를 쉽게 구축하기 위해 사양을 따르고 관련 종속성을 소개하면됩니다.
Spring Framework의 데이터베이스 작업은 JDBC에서 깊이 캡슐화되었습니다. 종속성 주입 기능을 통해 DataSource를 JDBCTemplate에 등록하여 객체 관계 매핑을 쉽게 완료하고 일반적인 오류를 피할 수 있습니다. SpringBoot에서는 쉽게 사용할 수 있습니다.
특징
수입 종속성
pom.xml의 jdbctemplate에 의존성을 추가하십시오
<! -Spring JDBC 종속성 패키지, 스프링 부트 스타터 -JDBC 또는 Spring-Boot-Starter-Data-JPA를 사용하는 Spring JDBC 의존성 패키지는 Hikaricp 의존성-> <crependency> <groupid> org.springframework.boot </groupIcid> <artifactid> spring-boot-starter-jdbc </aurefactid>를 자동으로 얻습니다. 패키지-> <pectinement> <groupId> mysql </groupId> <atrifactid> mySQL-connector-java </artifactId> </arepindency> <!-Tomcat은 기본 컨테이너에 의해 내장되어 있습니다. 컨테이너를 교체 해야하는 경우 매우 간단합니다. <artifactid> Spring-Boot-Starter-Web </artifactid> </fectionency>
데이터베이스에 연결하십시오
Application.Properties에 다음 구성을 추가하십시오. SpringBoot는 기본적으로 DataSource를 자동으로 구성하여 Hikaricp Connection Pool 사용의 우선 순위를 정할 것입니다. 의존성이없는 경우 Tomcat-JDBC를 선택하십시오. 처음 두 가지 중 어느 것도 사용할 수없는 경우 Commons DBCP2를 선택하십시오. Spring.datasource.Type 속성은 다른 유형의 연결 풀을 지정할 수 있습니다.
spring.datasource.url = jdbc : mysql : // localhost : 3306/chapter4? useUnicode = true & charac null & alluctiqueries = true & usessl = falsespring.datasource.password = rootspring.datasource.username = root#spring.datasource.type#more 미묘한 구성은 다음 접두사#spring.datasource.hikari#spring.datasource.tomcat#spring.datasource.dbcp2로 조정할 수 있습니다
로그를 통해 프로젝트를 시작하면 기본적으로 Hikaridatasource가 주입 된 것을 볼 수 있습니다.
2018-05-07 10 : 33 : 54.021 Info 9640 --- [Main] OsjeaAnnotationMbeanExporter : 이름을 가진 Bean ''DataSource '가 JMX Express 2018-05-07에 대해 자동으로 설정되었습니다. JMX 서버는 mbean [com.zaxxer.hikari : name = dataSource, type = hikaridatasource] 2018-05-07 10 : 33 : 54.071 정보 9640 --- [Main] OSBWEMBedded.TOMCAT.TOMCATWEBSERVER : 8080 (http)과 함께 시작했습니다. ''2018-05-07 10 : 33 : 54.075 정보 9640 --- [main] com.battcn.Chapter4application : 3.402 초 (JVM 실행) 3.93에 시작된 챕터 4 application을 시작했습니다.
특정 코드
기본 구성을 완료 한 후 특정 인코딩 작업을 수행하십시오. 코드의 양을 줄이기 위해 userdao 및 uservice와 같은 인터페이스를 작성하지 않습니다. 컨트롤러에서 직접 jdbctemplate을 사용하여 데이터베이스에 액세스합니다. 이것은 표준화되지 않았습니다. 나에게서 배우지 마십시오 ...
테이블 구조
t_user와 함께 테이블을 만듭니다
테이블 생성`t_user` (`id` int (8) not null auto_increment 댓글 '기본 키 증분',`username` varchar (50) null 댓글 'username',`varchar (50) null not noll not noll not not noll not not nont not not not not not not not not not not not not not nold nown a key (`id`)).
엔티티 클래스
패키지 com.battcn.entity;/** * @author levin * @since 2018/5/7 0007 */public class user {private long id; 개인 문자열 사용자 이름; 개인 문자열 비밀번호; // TODO 생략 GET SET}편안한 스타일 인터페이스
package com.battcn.controller; import com.battcn.entity.user; import org.springframework.beans.cortory.annotation.autowired; import org.springframework.jdbc.core.beanpropertyrowmapper; import org.springfringframework.jdbc.jdbctemplate; org.springframework.web.bind.annotation. @autowired public springjdbccontroller (jdbctemplate jdbctemplate) {this.jdbctemplate = jdbctemplate; } @GetMapping public list <user> queryUsers () {// 쿼리 모든 사용자 string sql = "select * from t_user"; return jdbctemplate.query (sql, new object [] {}, new beanpropertyrowmapper <> (user.class)); } @getMapping ( "/{id}") public user getUser (@pathVariable long id) {// query string sql = "select *에서 t_user where id =?"; return jdbctemplate.queryforobject (sql, new object [] {id}, new beanpropertyrowmapper <> (user.class)); } @deletemapping ( "/{id}") public int deLuser (@pathVariable long id) {// 기본 키 ID 문자열에 따라 사용자 정보 삭제 sql = "id =?"; return jdbctemplate.update (sql, id); } @postmapping public int adduser (@requestbody user user) {// 사용자 문자열 추가 sql = "t_user (username, password) 값 (?,?)에 삽입."; return jdbctemplate.update (sql, user.getusername (), user.getpassword ()); } @putMapping ( "/{id}") public int edituser (@pathvariable long id, @requestbody user user) {// 기본 키 ID 문자열 sql = "업데이트 t_user set username =?, password =? where id =?"; return jdbctemplate.update (sql, user.getusername (), user.getpassword (), id); }}시험
위의 인터페이스는 편안한 스타일의 인터페이스이므로 브라우저를 통해 추가 및 수정을 완료 할 수 없으므로 Junit 직접 작성하거나 Postman과 같은 도구를 사용해야합니다.
단위 테스트 제작 챕터 4ApplicationTests 및 TestRestTemplate를 통해 Get, Post, Put, Delete 등과 같은 요청 작업을 시뮬레이션하십시오.
패키지 com.battcn; import com.battcn.entity.user; import org.junit.test; import org.junit.runner.runwith; import org.slf4j.logger; import org.slf4j.logger explory; import org.springframework.beans.antofation org.springframework.boot.test.context.springboottest; import org.springframework.boot.test.web.client.testresttemplate; import org.springframework.boot.web.server.localserverport; import org.springframework.core.core.coremeterizeedtypereperferonate; org.springframework.http.httpmethod; import org.springframework.http.responsentity; import org.springframework.test.context.junit4.springrunner; import java.util.list;/*** @author levin */@runwith (springRunner.class) @SpringBootTest (classe = chaptess = chaptess, webenvironment = springboottest.webenvironment.random_port) public class 챕터 4applicationTests {private static final logger log = loggeractory.getLogger (chapter4applicationTests.class); @autowired private testRestTemplate 템플릿; @localserverport 개인 int 포트; @test public void test1 ()는 예외 {template.postforentity ( "http : // localhost :" + port + "/user", 새 사용자 ( "user1", "pass1"), intger.class); log.info ( "[[사용자 성공 추가]/n"); // 반환 된 컬렉션 인 경우 getforentity 대신 exchange를 사용하여 replistentity 유형을 강요해야합니다. 이는 response 유형을 강요해야합니다. 응답 <목록 <사용자 >> response.exchange ( "http : // localhost :" + port + "/users", httpmethod.get, null, new parameterizedtypereference <user >> () {}); 최종 목록 <user> body = response2.getbody (); log.info ( "[query all] - [{}]/n", body); long userId = body.get (0) .getId (); ResponseEntity <user> response3 = template.getforentity ( "http : // localhost :" + port + "/users/{id}", user.class, userId); log.info ( "[1 차 키 쿼리] - [{}]/n", response3.getBody ()); template.put ( "http : // localhost :" + port + "/user/{id}", 새 사용자 ( "user11", "pass11"), userId); log.info ( "[[사용자 수정 성공적으로]/n"); template.delete ( "http : // localhost :" + port + "/users/{id}", userId); log.info ( "[[성공적으로 삭제]"); }}요약
이 장에서는 JDBCTemplate의 일반적으로 사용되는 몇 가지 작업을 소개합니다. 자세한 내용은 JDBCTEMPLATE API 문서를 참조하십시오.
많은 Bigwig는 SpringBoot에 대한 자습서를 작성했습니다. 유사점이 있으면 용서 해주세요. 이 튜토리얼은 최신 스프링 부트 스타터 부모를 기반으로합니다 : 2.0.1. release, 새 버전의 기능이 함께 소개됩니다 ...