Spring Boot 连接MySql数据库

Spring Boot 以后也许会成为入门 Spring 的首选!

记一下 Spring Boot 成功连接 Mysql 数据库的方法步骤!

一、新建 Maven 工程,不全 Maven 所需文件夹,在 pom.xml 引入 SpringBoot 的依赖包!可以参照:http://www.cnblogs.com/liangblog/p/5207855.html

二、有两种方法与数据库建立连接,一种是集成 Mybatis,另一种用 JdbcTemplate

  (1)、用 JdbcTemplate

<dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
          </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
添加数据库依赖

 添加配置文件配置数据库和其他参数

  在 resource 文件夹下添加 application.properties 配置文件并输入数据库参数,如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8011
server.session.timeout
=10
server.tomcat.uri
-encoding=UTF-8

application.properties

 新建 Controller 类测试数据库连接

package com.lgp.SpringBoot;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mydb")
public class DbController {

@Autowired
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> JdbcTemplate jdbcTemplate;

@RequestMapping(</span>"/getUsers"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;Map&lt;String, Object&gt;&gt;<span style="color: rgba(0, 0, 0, 1)"> getDbType(){
    String sql </span>= "select * from appuser"<span style="color: rgba(0, 0, 0, 1)">;
    List</span>&lt;Map&lt;String, Object&gt;&gt; list =<span style="color: rgba(0, 0, 0, 1)">  jdbcTemplate.queryForList(sql);
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Map&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)"> map : list) {
        Set</span>&lt;Entry&lt;String, Object&gt;&gt; entries =<span style="color: rgba(0, 0, 0, 1)"> map.entrySet( );
            </span><span style="color: rgba(0, 0, 255, 1)">if</span>(entries != <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
                Iterator</span>&lt;Entry&lt;String, Object&gt;&gt; iterator =<span style="color: rgba(0, 0, 0, 1)"> entries.iterator( );
                </span><span style="color: rgba(0, 0, 255, 1)">while</span><span style="color: rgba(0, 0, 0, 1)">(iterator.hasNext( )) {
                Entry</span>&lt;String, Object&gt; entry =(Entry&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)">) iterator.next( );
                Object key </span>=<span style="color: rgba(0, 0, 0, 1)"> entry.getKey( );
                Object value </span>=<span style="color: rgba(0, 0, 0, 1)"> entry.getValue();
                System.out.println(key</span>+":"+<span style="color: rgba(0, 0, 0, 1)">value);
            }
        }
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

@RequestMapping(</span>"/user/{id}"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Map&lt;String,Object&gt;<span style="color: rgba(0, 0, 0, 1)"> getUser(@PathVariable String id){
    Map</span>&lt;String,Object&gt; map = <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    
    List</span>&lt;Map&lt;String, Object&gt;&gt; list =<span style="color: rgba(0, 0, 0, 1)"> getDbType();
    
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Map&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)"> dbmap : list) {
        
        Set</span>&lt;String&gt; set =<span style="color: rgba(0, 0, 0, 1)"> dbmap.keySet();
        
        </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (String key : set) {
            </span><span style="color: rgba(0, 0, 255, 1)">if</span>(key.equals("id"<span style="color: rgba(0, 0, 0, 1)">)){    
                </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)">(dbmap.get(key).equals(id)){
                    map </span>=<span style="color: rgba(0, 0, 0, 1)"> dbmap;
                }
            }
        }
    }
    
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(map==<span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">)
        map </span>= list.get(0<span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> map;
}

}

DbController.java

运行 App 输入地址 输出数据库数据。。。。。。

2)、集成 Mybatis

 添加 mybatis 依赖

 <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.0.0</version>
        </dependency>

版本号可能有更新!

在配置文件中添加配置信息:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8011
server.session.timeout
=10
server.tomcat.uri
-encoding=UTF-8

mybatis.config= classpath:mybatis-config.xml

mybatis.mapperLocations=classpath:mappers/*.xml

domain object's package

mybatis.typeAliasesPackage=com.lgp.SpringBoot.bean

handler's package

mybatis.typeHandlersPackage=

check the mybatis configuration exists

mybatis.check-config-location=

mode of execution. Default is SIMPLE

mybatis.executorType=

依次添加 mapper 的接口类和 xml 文件

主要代码:

package com.lgp.SpringBoot.mapper;

import java.util.List;

import com.lgp.SpringBoot.bean.AppMessage;

public interface AppMessageMapper {

</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> deleteByPrimaryKey(String id);

</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insert(AppMessage record);

</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> insertSelective(AppMessage record);

AppMessage selectByPrimaryKey(String id);

</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateByPrimaryKeySelective(AppMessage record);

</span><span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> updateByPrimaryKey(AppMessage record);

List</span>&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> selectAll();

List</span>&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getMessById(String id);

}

AppMessageMapper.java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lgp.SpringBoot.mapper.AppMessageMapper" >

<resultMap id="BaseResultMap" type="com.lgp.SpringBoot.bean.AppMessage" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="message" property="message" jdbcType="VARCHAR" />
<result column="senddate" property="senddate" jdbcType="TIMESTAMP" />
</resultMap>

<sql id="Base_Column_List" >
id, message, senddate
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from appuser_message
where id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from appuser_message
where id = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
insert into appuser_message (id, message, senddate
)
values (#{id,jdbcType=VARCHAR}, #{message,jdbcType=VARCHAR}, #{senddate,jdbcType=TIMESTAMP}
)
</insert>
<insert id="insertSelective" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
insert into appuser_message
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="message != null" >
message,
</if>
<if test="senddate != null" >
senddate,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=VARCHAR},
</if>
<if test="message != null" >
#{message,jdbcType=VARCHAR},
</if>
<if test="senddate != null" >
#{senddate,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
update appuser_message
<set >
<if test="message != null" >
message = #{message,jdbcType=VARCHAR},
</if>
<if test="senddate != null" >
senddate = #{senddate,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
update appuser_message
set message = #{message,jdbcType=VARCHAR},
senddate = #{senddate,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=VARCHAR}
</update>

<select id="selectAll" resultMap="BaseResultMap">
select
id, message, senddate
from appuser_message
order by senddate asc
</select>

<select id="getMessById" resultMap="BaseResultMap" parameterType="java.lang.String">
select
id, message, senddate
from
appuser_message
where id = #{id,jdbcType=VARCHAR}
order by senddate asc
</select>

</mapper>

AppMessageMapper.xml
package com.lgp.SpringBoot.bean;

import java.util.Date;

public class AppMessage {
private String id;

</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String message;

</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> Date senddate;

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getId() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> id;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setId(String id) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.id = id == <span style="color: rgba(0, 0, 255, 1)">null</span> ? <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)"> : id.trim();
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getMessage() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> message;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setMessage(String message) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.message = message == <span style="color: rgba(0, 0, 255, 1)">null</span> ? <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)"> : message.trim();
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Date getSenddate() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> senddate;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setSenddate(Date senddate) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.senddate =<span style="color: rgba(0, 0, 0, 1)"> senddate;
}

}

AppMessage.java
package com.lgp.SpringBoot.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lgp.SpringBoot.bean.AppMessage;
import com.lgp.SpringBoot.mapper.AppMessageMapper;

@Service
public class AppMessageService {

@Autowired
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> AppMessageMapper mapper;

</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getMessage(){
     List</span>&lt;AppMessage&gt; list = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)">();
     list.add(mapper.selectByPrimaryKey(</span>"xtt"<span style="color: rgba(0, 0, 0, 1)">));
     </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">list = mapper.selectAll();</span>
     <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getAllMessage(){
     List</span>&lt;AppMessage&gt; list = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)">();
     list </span>=<span style="color: rgba(0, 0, 0, 1)"> mapper.selectAll();
     </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> addMessage(AppMessage appMessage) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> mapper.insert(appMessage);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getMessageById(String id) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> mapper.getMessById(id);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> delMessage(String id) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> mapper.deleteByPrimaryKey(id);
}

}

AppMessageService.java
package com.lgp.SpringBoot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lgp.SpringBoot.bean.AppMessage;
import com.lgp.SpringBoot.service.AppMessageService;

@RestController
@RequestMapping("/appmessage")
public class APPMessageController {

@Autowired
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> AppMessageService service;

@RequestMapping(</span>"/getThree"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getThreeForMessage(){
    
    List</span>&lt;AppMessage&gt; list =<span style="color: rgba(0, 0, 0, 1)"> service.getMessage();        
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

@RequestMapping(</span>"/getAll"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt;<span style="color: rgba(0, 0, 0, 1)"> getAllMessage(){
    
    List</span>&lt;AppMessage&gt; list =<span style="color: rgba(0, 0, 0, 1)"> service.getAllMessage();
    </span><span style="color: rgba(0, 0, 255, 1)">int</span> num =<span style="color: rgba(0, 0, 0, 1)"> list.size();
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">null</span>!=list &amp;&amp; num&gt;3<span style="color: rgba(0, 0, 0, 1)">){
        </span><span style="color: rgba(0, 0, 255, 1)">for</span> (<span style="color: rgba(0, 0, 255, 1)">int</span> i = 0; i &lt; num-3; i++<span style="color: rgba(0, 0, 0, 1)">) {
            list.remove(</span>0<span style="color: rgba(0, 0, 0, 1)">);
        }
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

@RequestMapping(</span>"/getByID"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;AppMessage&gt; getMessageById(@RequestParam("id"<span style="color: rgba(0, 0, 0, 1)">) String id){
    List</span>&lt;AppMessage&gt; list =<span style="color: rgba(0, 0, 0, 1)"> service.getMessageById(id);
    </span><span style="color: rgba(0, 0, 255, 1)">int</span> num =<span style="color: rgba(0, 0, 0, 1)"> list.size();
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">null</span>!=list &amp;&amp; num&gt;5<span style="color: rgba(0, 0, 0, 1)">){
        </span><span style="color: rgba(0, 0, 255, 1)">for</span> (<span style="color: rgba(0, 0, 255, 1)">int</span> i = 0; i &lt; num-5; i++<span style="color: rgba(0, 0, 0, 1)">) {
            list.remove(</span>0<span style="color: rgba(0, 0, 0, 1)">);
        }
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list;
}

@RequestMapping(value </span>= "/add",method =<span style="color: rgba(0, 0, 0, 1)"> RequestMethod.POST)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> addMessage(@RequestBody AppMessage appMessage){
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> service.addMessage(appMessage);
}

@RequestMapping(value</span>="/delMessageById",method=<span style="color: rgba(0, 0, 0, 1)">RequestMethod.POST)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> delMessageById(@RequestParam("id"<span style="color: rgba(0, 0, 0, 1)">) String id){
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> service.delMessage(id);
}

}

APPMessageController.java

运行 App  输入地址测试,获取数据库数据......