落跃之城

书读万卷,路行万里;惜时如金,内外兼修。

SpringBoot框架与MyBatis集成,连接Mysql数据库

  SpringBoot是一种用来简化新Spring应用初始搭建及开发过程的框架,它使用特定方式来进行配置,使得开发人员不再需要定义样板化的配置。MyBatis是一个支持普通SQL查询、存储和高级映射的持久层框架,它消除了几乎所有的JDBC代码和参数的手工配置以及对结果集的检索封装,可以使用简单的XML或注解用于配置和原始映射,将接口和Java的对象映射成数据库中的记录。

  最近的项目有相关需求,集成SpringBoot和MyBatis框架后,进行Mysql数据库的数据访问,实现功能后总结于此博客,方便以后查看。

  首先下载一个SpringBoot的demo程序,然后在它上面集成,访问:demo下载,如下图所示,勾选Web选项后点击Generate Project即可下载工程。

  打开demo后可以更改项目名称,设置目录为如下图形式,其中需要的jar包自行下载,

  然后对每一个文件进行编辑,示例中有Disaster和Economic两部分内容,仅介绍Disaster部分原理即可。

  先构建Disaster类,根据Mysql中表的数据情况建立对象,Disaster.java代码如下:

 1 package smm.springboot.bean;
 2 
 3 public class Disaster {
 4     private int id;
 5     private String deathtoll;//死亡人数
 6     private String injuriesnumber;//受伤人数
 7     private String disappearancenumber;//失踪人数
 8     private String total;//总人数
 9     private String did;
10     public int getId() {
11         return id;
12     }
13     public void setId(int id) {
14         this.id = id;
15     }
16     public String getDeathtoll() {
17         return deathtoll;
18     }
19     public void setDeathtoll(String deathtoll) {
20         this.deathtoll = deathtoll;
21     }
22     public String getInjuriesnumber() {
23         return injuriesnumber;
24     }
25     public void setInjuriesnumber(String injuriesnumber) {
26         this.injuriesnumber = injuriesnumber;
27     }
28     public String getDisappearancenumber() {
29         return disappearancenumber;
30     }
31     public void setDisappearancenumber(String disappearancenumber) {
32         this.disappearancenumber = disappearancenumber;
33     }
34     public String getTotal() {
35         return total;
36     }
37     public void setTotal(String total) {
38         this.total = total;
39     }
40     public String getDid() {
41         return did;
42     }
43     public void setDid(String did) {
44         this.did = did;
45     } 
46 }

  接下来是Mybatis的接口DisasterMapper.java,代码如下:

 1 package smm.springboot.mapper;
 2 import org.apache.ibatis.annotations.Mapper;
 3 
 4 import smm.springboot.bean.Disaster;
 5 
 6 @Mapper
 7 public interface DisasterMapper {    
 8     public void insert(Disaster disaster);//插入数据
 9     public Disaster find(int id);//查找数据
10 }

  对应的mapper文件,DisasterMapper.xml,插入数据和查找数据的程序都是在这个XML文件中生成,代码如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 
 4 <mapper namespace="smm.springboot.mapper.DisasterMapper">
 5     <!-- insert disaster -->
 6     <insert id="insert" parameterType="smm.springboot.bean.Disaster">
 7         INSERT INTO d_disaster_overview(deathtoll,injuriesnumber,disappearancenumber,total,did) VALUE(#{deathtoll},#{injuriesnumber},#{disappearancenumber},#{total},#{did});
 8     </insert>
 9     
10     <!-- find disaster -->
11     <select id="find" parameterType="int" resultType="smm.springboot.bean.Disaster">
12         SELECT sum(deathtoll) as deathtoll,sum(injuriesnumber) as injuriesnumber,sum(disappearancenumber) as disappearancenumber, sum(total) as total FROM d_disaster_overview WHERE ID=#{id}
13     </select>
14 </mapper>

  然后是业务层的接口与实现类,DisasterIService.java的代码如下:

 1 package smm.springboot.service;
 2 import org.springframework.stereotype.Component;
 3 import org.springframework.web.servlet.DispatcherServlet;
 4 
 5 import smm.springboot.bean.Disaster;
 6 
 7 public interface DisasterIService{
 8     
 9     public boolean insert(Disaster disaster);
10     public Disaster find(int id);
11 }

  DisasterService.java的代码如下:

 1 package smm.springboot.service.impl;
 2 
 3 import javax.annotation.Resource;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.stereotype.Service;
 6 
 7 import smm.springboot.bean.Disaster;
 8 import smm.springboot.mapper.DisasterMapper;
 9 import smm.springboot.service.DisasterIService;
10 
11 @ComponentScan({"smm.springboot.mapper"})
12 @Service("disasterService")
13 public class DisasterService implements DisasterIService{
14     @Resource
15     private DisasterMapper disasterMapper;
16     @Override
17     public boolean insert(Disaster disaster) {
18         
19         try {
20             disasterMapper.insert(disaster);
21         } catch (Exception e) {
22             //TODO Auto-generated catch block
23             return false;
24         }
25         return true;
26     }
27     @Override
28     public Disaster find(int id) {
29         return disasterMapper.find(id);
30     }
31 }

  接下来是比较重要的前端控制器AllController.java,它之中关于Disaster的部分代码如下:

 1 package com.example.demo;
 2 
 3 import javax.annotation.Resource;
 4 import org.mybatis.spring.annotation.MapperScan;
 5 import org.springframework.context.annotation.ComponentScan;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.ResponseBody;
 9 import com.google.gson.JsonObject;
10 
11 import smm.springboot.bean.*;
12 import smm.springboot.service.impl.*;
13 
14 @Controller
15 @ComponentScan({"smm.springboot.service"})
16 @MapperScan({"smm.springboot.mapper"})
17 public class AllController {
18 
19     @Resource
20     private DisasterService disasterService;
21     //Disaster部分
22     @RequestMapping("/DisasterSaveresult")
23     @ResponseBody
24     public String helloD(Disaster disaster) {
25         boolean result=disasterService.insert(disaster);
26         JsonObject json=new JsonObject();
27         if(result){
28             json.addProperty("manager", "添加成功");
29             json.addProperty("result", "1");
30         }else{
31             json.addProperty("manager", "添加失败");
32             json.addProperty("result", "0");
33         }
34         return json.toString();
35     }    
36     @RequestMapping("/DisasterFind")  
37     @ResponseBody
38     public String sayD(int id){
39         Disaster d=disasterService.find(id);
40         JsonObject json=new JsonObject();
41         json.addProperty("deathtoll", d.getDeathtoll());
42         json.addProperty("injuriesnumber", d.getInjuriesnumber());
43         json.addProperty("disappearancenumber", d.getDisappearancenumber());
44         json.addProperty("total", d.getTotal());
45         return json.toString();
46     }
47     @RequestMapping("/DisasterSave")
48     public String jspD() {
49         return "DisasterIndex";
50     }
51 }
View Code

  还有ServletInitializer.java,其代码如下:

 1 package com.example.demo;
 2 
 3 import org.springframework.boot.builder.SpringApplicationBuilder;
 4 import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;;
 5 
 6 public class ServletInitializer extends org.springframework.boot.web.servlet.support.SpringBootServletInitializer{
 7     @Override
 8     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
 9         return application.sources(this.getClass());
10     }
11 }

  还有SpringBoot的配置文件application.properties,内容如下:

server.context-path=/HelloWorld

spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.datasource.url =jdbc:mysql://10.10.10.7:3306/mysql
spring.datasource.username =name
spring.datasource.password =password
      
mybatis.typeAliasesPackage=smm.springboot.bean  
mybatis.mapperLocations=classpath:mapper/*Mapper.xml

spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
View Code

  还有maven项目的配置文件pom.xml,内容如下:

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4     <modelVersion>4.0.0</modelVersion>
  5  
  6     <groupId>disaster</groupId>
  7     <artifactId>disaster</artifactId>
  8     <version>0.0.1-SNAPSHOT</version>
  9     <packaging>war</packaging>
 10  
 11     <name>springbootone</name>
 12     <url>http://maven.apache.org</url>
 13  
 14     <properties>
 15         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 16     </properties>
 17  
 18     <!-- 添加springboot继承 -->
 19     <parent>
 20         <groupId>org.springframework.boot</groupId>
 21         <artifactId>spring-boot-starter-parent</artifactId>
 22         <version>2.1.0.RELEASE</version>
 23     </parent>
 24  
 25     <dependencies>
 26         <!-- 添加springMVC支持 -->
 27         <dependency>
 28             <groupId>org.springframework.boot</groupId>
 29             <artifactId>spring-boot-starter-web</artifactId>
 30         </dependency>
 31         <!-- MySQL -->
 32         <dependency>
 33             <groupId>mysql</groupId>
 34             <artifactId>mysql-connector-java</artifactId>
 35             <version>5.1.19</version>
 36         </dependency>
 37         <!-- mybatis -->
 38     <dependency>
 39         <groupId>org.mybatis</groupId>
 40         <artifactId>mybatis</artifactId>
 41         <version>3.4.5</version>
 42     </dependency>
 43     <dependency>
 44         <groupId>org.mybatis</groupId>
 45         <artifactId>mybatis-spring</artifactId>
 46         <version>1.3.1</version>
 47     </dependency>
 48     <dependency>
 49         <groupId>org.springframework</groupId>
 50         <artifactId>spring-webmvc</artifactId>
 51         <version>5.1.2.RELEASE</version>
 52     </dependency>
 53     <dependency>
 54         <groupId>org.springframework</groupId>
 55         <artifactId>spring-tx</artifactId>
 56         <version>5.1.2.RELEASE</version>
 57     </dependency>
 58     <dependency>
 59         <groupId>org.apache.logging.log4j</groupId>
 60         <artifactId>log4j-core</artifactId>
 61         <version>2.7</version>
 62     </dependency>
 63     <dependency>
 64         <groupId>com.alibaba</groupId>
 65         <artifactId>druid</artifactId>
 66         <version>1.1.6</version>
 67     </dependency>
 68     <dependency>
 69         <groupId>org.springframework</groupId>
 70         <artifactId>spring-jdbc</artifactId>
 71         <version>5.0.2.RELEASE</version>
 72     </dependency>
 73     <dependency>
 74             <groupId>org.mybatis.spring.boot</groupId>
 75             <artifactId>mybatis-spring-boot-starter</artifactId>
 76             <version>1.2.0</version>
 77         </dependency>
 78         <dependency>
 79             <groupId>org.springframework.boot</groupId>
 80             <artifactId>spring-boot-starter-web</artifactId>
 81         </dependency>
 82         <!-- tomcat支持 -->
 83        <dependency>
 84            <groupId>org.springframework.boot</groupId>
 85            <artifactId>spring-boot-starter-tomcat</artifactId>
 86            <scope>provided</scope>
 87        </dependency>
 88        <dependency>
 89            <groupId>org.apache.tomcat.embed</groupId>
 90            <artifactId>tomcat-embed-jasper</artifactId>
 91            <scope>provided</scope>
 92        </dependency>
 93         <!-- jsp标签库 -->
 94         <dependency>
 95            <groupId>javax.servlet</groupId>
 96            <artifactId>jstl</artifactId>
 97        </dependency>
 98       <dependency>
 99         <groupId>com.google.code.gson</groupId>
100         <artifactId>gson</artifactId>
101         <version>2.8.0</version>
102       </dependency>
103     </dependencies>
104  
105     <build>
106         <finalName>BOOT</finalName>
107         <plugins>
108             <!-- 引入java编译器插件 -->
109             <plugin>
110                 <groupId>org.apache.maven.plugins</groupId>
111                 <artifactId>maven-compiler-plugin</artifactId>
112                 <configuration>
113                     <source>1.8</source>
114                     <target>1.8</target>
115                     <compilerVersion>1.8</compilerVersion>
116                     <encoding>UTF-8</encoding>
117                 </configuration>
118             </plugin>
119             <!-- 资源文件拷贝插件 -->
120             <plugin>
121                 <groupId>org.apache.maven.plugins</groupId>
122                 <artifactId>maven-resources-plugin</artifactId>
123                 <configuration>
124                     <encoding>UTF-8</encoding>
125                 </configuration>
126             </plugin>
127         </plugins>
128     </build>
129 </project>

  另外还配置了一个用来输入数据的页面DisasterIndex.jsp,目录如下图:

  内容代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <title>输入灾害数据</title>
 7 </head>
 8 <body>
 9     <h1>Please input disaster data!</h1>
10     <form action="DisasterSaveresult" name="form">
11         <p>
12         <table border="1">
13             <tr>
14                 <td>死亡人数</td>
15                 <td>受伤人数</td>
16                 <td>失踪人数</td>
17                 <td>总人数</td>
18                 <td>Did</td>
19             </tr>
20             <tr>
21                 <td><input name="deathtoll" type="text" /></td>
22                 <td><input name="injuriesnumber" type="text" /></td>
23                 <td><input name="disappearancenumber" type="text" /></td>
24                 <td><input name="total" type="text" /></td>
25                 <td><input name="did" value="1" type="text" /></td>
26             </tr>
27         </table>
28         </p>
29         <tr>
30             <td><input type="submit" value="确定" size="50" /></td>
31             <td><input type="reset" value="取消" size="50" /></td>
32         </tr>
33     </form>
34 </body>
35 </html>

  最后是程序启动类DemoApplication.java,内容如下:

 1 package com.example.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import java.net.*;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 import java.io.FileOutputStream;  
 9 import java.io.InputStream; 
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 
13 import org.apache.http.HttpEntity;
14 import org.apache.http.HttpResponse;
15 import org.apache.http.NameValuePair;
16 import org.apache.http.client.HttpClient;
17 import org.apache.http.client.methods.HttpGet; 
18 import org.apache.http.client.entity.UrlEncodedFormEntity;
19 import org.apache.http.client.methods.HttpPost;
20 import org.apache.http.impl.client.DefaultHttpClient;
21 import org.apache.http.message.BasicNameValuePair;
22 import org.apache.http.util.EntityUtils;
23 import org.codehaus.jettison.json.JSONObject;
24 
25 
26 @SpringBootApplication
27 public class DemoApplication {
28     public static void main(String[] args) {
29         SpringApplication.run(DemoApplication.class, args);
30     }
31 }

  点击Run As Java Application后启动,可看到如下信息:

  在浏览器输入http://localhost:8080//DisasterSave,得到以下页面,便可在表格中输入数据并插入到Mysql数据库的表中。

  至此,整个工程已经完成!

 

posted on 2018-11-06 22:37  落跃之城  阅读(4570)  评论(0编辑  收藏  举报

导航