Refer to the official example: http://spring.io/guides/gs/relational-data-access/
1. Project preparation
Create a new table "t_order" after creating mysql database
SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `t_order`-- ----------------------------DROP TABLE IF EXISTS `t_order`;CREATE TABLE `t_order` ( `order_id` varchar(36) NOT NULL, `order_no` varchar(50) DEFAULT NULL, `order_date` datetime DEFAULT NULL, `quantity;` int(11) DEFAULT NULL, PRIMARY KEY (`order_id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- ------------------------------ Records of t_order-- ----------------------------
Modify 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/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.carter659</groupId> <artifactId>spring04</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring04</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
2. Write class files:
Modify App.java
package com.github.carter659.spring04;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * Blog source: http://www.cnblogs.com/GoodHelper/ * * @author Liu Dong* */@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}Create a new data carrier file "Order.java"
package com.github.carter659.spring04;import java.util.Date;/** * Blog source: http://www.cnblogs.com/GoodHelper/ * @author Liu Dong* */public class Order { public String id; public String no; public Date date; public int quantity; /** * Omit get set */}Create a new data persistence layer class "OrderDao.java"
package com.github.carter659.spring04;import java.util.ArrayList;import java.util.List;import java.util.UUID;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.support.rowset.SqlRowSet;import org.springframework.stereotype.Repository;/** * Blog source: http://www.cnblogs.com/GoodHelper/ * @author Liu Dong* */@Repositorypublic class OrderDao { @Autowired private JdbcTemplate jdbcTemplate; public List<Order> findAll() { List<Order> list = new ArrayList<>(); String sql = " select * from t_order "; SqlRowSet rows = jdbcTemplate.queryForRowSet(sql, new Object[] {}); while (rows.next()) { Order order = new Order(); list.add(order); order.id = rows.getString("order_id"); order.no = rows.getString("order_no"); order.date = rows.getDate("order_date"); order.quantity = rows.getInt("quantity"); } return list; } public Order get(String id) { Order order = null; String sql = " select * from t_order where order_id = ? "; SqlRowSet rows = jdbcTemplate.queryForRowSet(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("quantity"); } return order; } public String insert(Order order) { String id = UUID.randomUUID().toString(); String sql = " insert into t_order ( order_id , order_no , order_date , quantity ) values (?,?,?,?) "; jdbcTemplate.update(sql, new Object[] { id, order.no, new java.sql.Date(order.date.getTime()), order.quantity }); return id; } public void update(Order order) { String sql = " update 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 = " delete from t_order where order_id = ? "; jdbcTemplate.update(sql, new Object[] { id }); }}The operations on the database, as the name suggests:
findAll-->Query all data
get-->Get data through id
insert-->Insert data
update-->Modify data
delete-->Delete data
Create a new controller "MainController.java"
package com.github.carter659.spring04;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import 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;@Controllerpublic class MainController { @Autowired private 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); return result; } @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); return result; }}3. Create a new thymeleaf template
Create a new file "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>Play spring boot--combined with JDBC</title><script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script><script type="text/javascript"> /*<![CDATA[*/ var app = angular.module('app', []); app.controller('MainController', function($rootScope, $scope, $http) { $scope.data = {}; $scope.rows = []; //Add $scope.add = function() { $scope.data = { no : 'No.1234567890', quantity : 100, 'date' : '2016-12-30' }; } //Edit $scope.edit = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.data = row; return; } } } //Remove $scope.remove = function(id) { for ( var i in $scope.rows) { var row = $scope.rows[i]; if (id == row.id) { $scope.rows.splice(i, 1); return; } } } //Save $scope.save = function() { $http({ url : '/save', method : 'POST', data : $scope.data }).success(function(r) { //Update data after saving successfully $scope.get(r.id); }); } //Delete $scope.del = function(id) { $http({ url : '/delete?id=' + id, method : 'POST', }).success(function(r) { //Remove the data after deletion success$scope.remove(r.id); }); } //Get data$scope.get = function(id) { $http({ url : '/get?id=' + id, method : 'POST', }).success(function(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; } } $scope.rows.push(data); }); } //Initialize the load data $http({ url : '/findAll', method : 'POST' }).success(function(rows) { for ( var i in rows) { var row = rows[i]; $scope.rows.push(row); } }); }); /*]]>*/</script></head><body ng-app="app" ng-controller="MainController"> <h1>Play spring boot--Combined with JDBC</h1> <h4> <a href="http://www.cnblogs.com/GoodHelper/">from Liu Dong's blog</a> </h4> <input type="button" value="add" ng-click="add()" /> <input type="button" value="Save" ng-click="save()" /> <br /> <br /> <h3> List information: </h3> <input id="id" type="hidden" ng-model="data.id" /> <table cellpacing="1" style="background-color: #a0c6e5"> <tr> <td>No.: </td> <td><input id="no" ng-model="data.no" /></td> <td>Date: </td> <td><input id="date" ng-model="data.date" /></td> <td>Quantity: </td> <td><input id="quantity" ng-model="data.quantity" /></td> </tr> </table> <br /> <h3>List list: </h3> <table cellpacing="1" style="background-color: #a0c6e5"> <tr style="text-align: center; COLOR: #0076C8; BACKGROUND-COLOR: #F4FAFF; font-weight: bold"> <td>Operation</td> <td>Number</td> <td>Date</td> <td>Quantity</td> </tr> <ttr ng-repeat="row in rows" bgcolor='#F4FAFF'> <td><input ng-click="edit(row.id)" value="edit" type="button" /><input ng-click="del(row.id)" value="delete" type="button" /></td> <td>{{row.no}}</td> <td>{{row.date}}</td> <td>{{row.quantity}}</td> </tr> </table> <br /> <a href="http://www.cnblogs.com/GoodHelper/">Click to access the original blog</a></body></html>Use angularjs' ajax to call the background method of spring boot mv.
4. Database connection
Create a new "src/main/resources/application.properties" file
spring.datasource.initialize=falsespring.datasource.url=jdbc:mysql://localhost:3306/demospring.datasource.username=rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.Driver
The complete structure is:
5. Operation effect
Enter "http://localhost:8080/" in your browser
Add data:
Save new data:
Edit data:
Delete data:
Delete the effect of completion:
Code: https://github.com/carter659/spring-boot-04.git
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.