공식 예를 참조하십시오 : http://spring.io/guides/gs/relational-data-access/
1. 프로젝트 준비
MySQL 데이터베이스를 작성한 후 새 테이블 "t_order"를 만듭니다
SET FORESTER_KEY_CHECKS = 0; --------------------------`T_ORDER`-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`t_ord` int (11) 기본 널, 기본 키 (`order_id`)) 엔진 = myisam 기본 charset = utf8;--------------------------------------------------------------------------------------------------------------------------------
pom.xml을 수정하십시오
<project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : schemalocation = "http://maven.apache.org/pom/0.0.0.0 http://maven.apache.org/xsd/maven-4.0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> com.github.carter659 </groupid> <artifactid> spring04 </artifactid> <버전> 0.0.1-1-1-snapshot </version> <이름> Spring04 </name> <Url> http://maven.apache.org </url> <부모> <periid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <version> 1.4.20 </parent> <properties> <project.build.sourceencoding> utf-8 </project.build.build.sourceencoding> <java.version> 1.8 </java.version> </properties> <pectionals> <pectionency> <groupid> org.spramework.spramework.boot </group-webboot> spring-webbot> spring-starter-weeb> <pectionency> <groupId> org.springframework.boot </groupid> <artifactid> spring-boot-devtools </artifactid> <pectional> true </옵션> </expendency> <groupId> org.springframewort.boot.spramework.spramework.springframewort> spring-boot-statter- </artifactid> <pectionency> <groupid> org.springframework.boot </groupid> <artifactid> Spring-Boot-Starter-jdbc </artifactid> </dependency> <groupid> mysql </groupid> <tritifactid> mySQL-Connector-Java </arepifactid> </delpitency> <groupid> commons-dbcp </groupid> <artifactid> commons-dbcp </artifactid> </fectionement> </fectionements> <build> <plugins> <grugin> <groupin> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin> </flugin> </flufactid> </빌드> </project>
2. 클래스 파일 쓰기 :
app.java를 수정하십시오
package com.github.carter659.spring04; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootapplication;/** * 블로그 출처 : http://www.cnblogs.com/goodhelper/ * @author liu dong * @author */@SpringBootApplicationPublic Class App {public static void main (String [] args) {springApplication.Run (App.Class, args); }}새 데이터 캐리어 파일 "Order.java"생성
package com.github.carter659.spring04; import java.util.date;/** * 블로그 출처 : http://www.cnblogs.com/goodhelper/ * @author liu dong * */public string id; 공개 문자열 번호; 공개 날짜; 공개 int 수량; /** * 생략 설정 */}
새 데이터 지속성 계층 클래스 "orderdao.java"생성
package com.github.carter659.spring04; import java.util.arraylist; import java.util.list; import java.util.uuid; import org.spramframework.beans.annotation.autowired; import org.springframework.core.jdbctemplate; org.springframework.jdbc.support.rowset.sqlrowset; import org.spramframework.stereotype.repository;/** * 블로그 출처 : http://www.cnblogs.com/goodhelper/ * @author liu dong * */ @repository public classddao { @autower jdbctem jdbctemplate; 공개 목록 <dert> findall () {list <order> list = new ArrayList <> (); 문자열 sql = "select * from t_order"; sqlrowset rows = jdbctemplate.queryforresset (sql, new Object [] {}); while (rows.next ()) {order order = new Order (); list.add (주문); order.id = rows.getstring ( "order_id"); order.no = rows.getString ( "order_no"); order.date = rows.getDate ( "order_date"); order.quantity = rows.getint ( "수량"); } 반환 목록; } public Order get (string id) {order order = null; 문자열 sql = "select * from t_order where order_id =?"; sqlrowset rows = jdbctemplate.queryforseset (sql, new Object [] {id}); while (rows.next ()) {order = new order (); order.id = rows.getstring ( "order_id"); order.no = rows.getString ( "order_no"); order.date = rows.getDate ( "order_date"); order.quantity = rows.getint ( "수량"); } 반환 주문; } public String insert (Order Order) {String id = uuid.randomUuid (). toString (); 문자열 sql = "t_order (order_id, order_no, order_date, quartity) 값 (?,?,?,?)"; jdbctemplate.update (sql, new Object [] {id, order.no, new java.sql.date (order.date.gettime ()), Order.Quantity}); 반환 ID; } public void update (Order Order) {String sql = "업데이트 t_order set order_no =?, order_date =?, Quantity =? where order_id =?"; jdbctemplate.update (sql, new Object [] {order.no, new java.sql.date (order.date.gettime ()), order.quantity, order.id}); } public void delete (string id) {String sql = "order_id =? jdbctemplate.update (sql, new Object [] {id}); }}이름에서 알 수 있듯이 데이터베이스의 작업은 다음과 같습니다.
findall-> 모든 데이터를 쿼리하십시오
GET-> ID를 통해 데이터를 가져옵니다
삽입-> 데이터 삽입
업데이트-> 데이터 수정
삭제-> 데이터 삭제
새 컨트롤러 만들기 "maincontroller.java"
패키지 com.github.carter659.spring04; import java.util.hashmap; import java.util.map; import org.springframework.beans.beans.annotation.autowired; import org.spramepramework.stereotyp.controller; import org.springframework.web.bind.bind.bint org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.responsebody; import com.mysql.jdbc.stringUtils; @controllic ClassPublic Maincontroller Orderdao Orderdao; @getMapping ( "/") public String index () {return "index"; } @postmapping ( "/save") public @ResponseBody map <string, object> save (@requestbody order order) {map <string, object> result = new Hashmap <> (); if (stringUtils.isnullorEmpty (order.id)) order.id = orderdao.insert (Order); else {orderdao.update (Order); } result.put ( "id", order.id); 반환 결과; } @postmapping ( "/get") public @ResponseBody Object get (string id) {return orderdao.get (id); } @postmapping ( "/findall") public @ResponseBody Object findAll () {return orderdao.findall (); } @postmapping ( "/delete") public @ResponseBody map <string, object> delete (string id) {map <String, object> result = new Hashmap <> (); Orderdao.delete (id); result.put ( "id", id); 반환 결과; }}3. 새로운 Thymeleaf 템플릿을 만듭니다
새 파일 만들기 "src/main/resources/templates/index.html"
<! docType html> <html xmlns : th = "http://www.thymeleaf.org"> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"/> <title> Jdbc </title> </title </title-combined. src = "// cdn.bootcss.com/angular.js/1.5.6/angular.min.js">/script> <script 유형 ="text/javaScript ">/*<! app.controller ( 'maincontroller', function ($ rootscope, $ scope, $ http) {$ scope.data = {}; $ scope.rows = []; // add $ scope.add = function () {$ scope.data = {no : 'no.1234567890', Quantity : 100, '' ''}; // $ scope.edit = for (var i in $ scope.rows) {var row = $ scope.data = row; (id == row.id) {$ scope.rows.splice (i, 1)}}}} {url : '/save', 'post', data : $ scope.data}); // $ scope.del = function (id) {$ http ({url : '/delete? id =' + id, 메소드 : 'post',}). 성공 (r) {// 삭제 후 데이터를 제거합니다. '/get? id =' + id, method : 'post',}). 성공 (함수 (data) {for (var i in $ scope.rows) {var row = $ scope.rows [i]; if (data.id == row.id) {row.no = data.no; row.date = data.date; row.quantity = data.quantity; return; });}; /*]]]>*/</script> </head> <body ng-app = "app"ng-controller = "maincontroller"> <h1> 스프링 부츠 재생-jdbc </h1> <h4> <a href = "http://www.cnblogs.com/goodhelper/"> from Liu d 's blog "> <input type = "button"value = "add"ng-click = "add ()" /> <input type = "button"value = "save"ng-click = "save ()" /> <br /> <br /> <h3> List Information : < /h3> <입력 id = "id" ""Hidden "ng-model ="data.id ". #a0c6e5 "> <tr> <td> no. : </td> <td> <input id ="no "ng-model ="data.no "/> </td> <td> date : </td> <td> <input ="date "ng-model ="data.date "/> id = "수량"ng-model = "data.quantity"/> </td> </tr> </table> <br/> <h3> 목록 목록 : </h3> <table cellpacing = "1"style = "background-color : #a0c6e5"> <tr style = "text-align : center : #0076c8; <td> 작동 </td> <td> 번호 </td> </td> <td> 날짜 </td> <td> 수량 </td> </tr> <ttr ng-repeat = "행"행 ng-click = "del (row.id)"value = "delete"type = "button"/> </td> <td> {{row.no}} </td> <td> {{row.date}} </td> {row.quantity} </td> </tab> <br/> <a. href = "http://www.cnblogs.com/goodhelper/"> 원본 블로그에 액세스하려면 클릭하십시오 </a> </body> </html>angularjs의 ajax를 사용하여 스프링 부트 MV의 배경 메소드를 호출하십시오.
4. 데이터베이스 연결
새 "SRC/Main/Resources/Application.Properties"파일을 만듭니다
spring.datasource.initialize = falsespring.datasource.url = jdbc : mysql : // localhost : 3306/demospring.datasource.username = rootspring.datasource.password = spring.datasource.datasource.diverclass-name = com.mysql.jdbc.driver
완전한 구조는 다음과 같습니다.
5. 작동 효과
브라우저에 "http : // localhost : 8080/"를 입력하십시오
데이터 추가 :
새로운 데이터 저장 :
데이터 편집 :
데이터 삭제 :
완료 효과 삭제 :
코드 : https://github.com/carter659/spring-boot-04.git
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.