欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-09 14:04:58
SpringBoot是一种用来简化新Spring应用初始搭建及开发过程的框架,它使用特定方式来进行配置,使得开发人员不再需要定义样板化的配置。MyBatis是一个支持普通SQL查询、存储和高级映射的持久层框架,它消除了几乎所有的JDBC代码和参数的手工配置以及对结果集的检索封装,可以使用简单的XML ......

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

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

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

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

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

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

  然后对每一个文件进行编辑,示例中有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的部分代码如下:

SpringBoot框架与MyBatis集成,连接Mysql数据库
 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,内容如下:

SpringBoot框架与MyBatis集成,连接Mysql数据库
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,目录如下图:

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

  内容代码如下:

 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后启动,可看到如下信息:

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

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

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

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