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
private JdbcTemplate jdbcTemplate; @RequestMapping("/getUsers")
public List<Map<String, Object>> getDbType(){
String sql = "select * from appuser";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
} @RequestMapping("/user/{id}")
public Map<String,Object> getUser(@PathVariable String id){
Map<String,Object> map = null; List<Map<String, Object>> list = getDbType(); for (Map<String, Object> dbmap : list) { Set<String> set = dbmap.keySet(); for (String key : set) {
if(key.equals("id")){
if(dbmap.get(key).equals(id)){
map = dbmap;
}
}
}
} if(map==null)
map = list.get(0);
return 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 {

    int deleteByPrimaryKey(String id);

    int insert(AppMessage record);

    int insertSelective(AppMessage record);

    AppMessage selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(AppMessage record);

    int updateByPrimaryKey(AppMessage record);

    List<AppMessage> selectAll();

    List<AppMessage> 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; private String message; private Date senddate; public String getId() {
return id;
} public void setId(String id) {
this.id = id == null ? null : id.trim();
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message == null ? null : message.trim();
} public Date getSenddate() {
return senddate;
} public void setSenddate(Date senddate) {
this.senddate = 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
private AppMessageMapper mapper; public List<AppMessage> getMessage(){
List<AppMessage> list = new ArrayList<AppMessage>();
list.add(mapper.selectByPrimaryKey("xtt"));
//list = mapper.selectAll();
return list;
} public List<AppMessage> getAllMessage(){
List<AppMessage> list = new ArrayList<AppMessage>();
list = mapper.selectAll();
return list;
} public int addMessage(AppMessage appMessage) {
return mapper.insert(appMessage);
} public List<AppMessage> getMessageById(String id) {
return mapper.getMessById(id);
} public int delMessage(String id) {
return 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
private AppMessageService service; @RequestMapping("/getThree")
public List<AppMessage> getThreeForMessage(){ List<AppMessage> list = service.getMessage();
return list;
} @RequestMapping("/getAll")
public List<AppMessage> getAllMessage(){ List<AppMessage> list = service.getAllMessage();
int num = list.size();
if(null!=list && num>3){
for (int i = 0; i < num-3; i++) {
list.remove(0);
}
}
return list;
} @RequestMapping("/getByID")
public List<AppMessage> getMessageById(@RequestParam("id") String id){
List<AppMessage> list = service.getMessageById(id);
int num = list.size();
if(null!=list && num>5){
for (int i = 0; i < num-5; i++) {
list.remove(0);
}
}
return list;
} @RequestMapping(value = "/add",method = RequestMethod.POST)
public int addMessage(@RequestBody AppMessage appMessage){
return service.addMessage(appMessage);
} @RequestMapping(value="/delMessageById",method=RequestMethod.POST)
public int delMessageById(@RequestParam("id") String id){
return service.delMessage(id);
}
}

APPMessageController.java

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

Spring Boot 连接MySql数据库的更多相关文章

  1. Spring Boot连接MySQL数据库

    上篇 只需两步!Eclipse+Maven快速构建第一个Spring Boot项目 已经构建了一个Spring Boot项目,本文在此基础上进行连接MySQL数据库的操作. 1. pom.xml添加依 ...

  2. Spring Boot连接Mysql数据库问题解决

    在spring Boot项目中使用mysql数据库进行数据库的增删查改,出现以下错误: Error starting ApplicationContext. To display the auto-c ...

  3. spring boot 连接Mysql介绍

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  4. Spring Boot连接MySQL长时间不连接后报错`com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.`的解决办法

    报错:com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection ...

  5. spring boot 连接mysql 错误The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one

    1.spring boot 整合mybatis 连接mysql时错误 The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or repr ...

  6. Java框架spring Boot学习笔记(四):Spring Boot操作MySQL数据库

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

  7. Java框架spring Boot学习笔记(五):Spring Boot操作MySQL数据库增、删、改、查

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

  8. IntelliJ IDEA通过Spring配置连接MySQL数据库

    先从菜单View→Tool Windows→Database打开数据库工具窗口,如下图所示: 点击Database工具窗口左上角添加按钮"+",选择Import from sour ...

  9. Spring Boot连接MySQL报错“Internal Server Error”的解决办法

    报错信息如下: {timestamp: "2018-06-14T03:48:23.436+0000", status: 500, error: "Internal Ser ...

随机推荐

  1. android ListView 和 BaseAdapter 应用

    步聚: 1.建立ListView对象:--(作用:绑定Adapter呈现数据) 2.建立ListView实现的Item栏位.xml布局:--(作用:实现ListView的栏位布局) 3.建立Item. ...

  2. android RelativeLayout 动态设置高度

    定义: private RelativeLayout mrlay; 调高度: mrlay = (RelativeLayout) findViewById(R.id.rlay_1); android.v ...

  3. 9、FTP封杀用户、限制传输速率、限制访问目录、为匿名用户提供下载资源

    一.封杀某些用户访问FTP服务器 例如  封杀 yanji [root@localhost root]#   vi   /etc/vsftpd.ftpusers     (用户控制配置文件,主要用于限 ...

  4. [译] OpenStack Liberty 版本中的53个新变化

    一个新的秋季,一个新的OpenStack 版本.OpenStack 的第12个版本,Liberty,在10月15日如期交付,而且目前发行版本已经备好了.那么我们期望能从过去六个月时间的开发中获得些什么 ...

  5. poj2486Apple Tree[树形背包!!!]

    Apple Tree Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 9989   Accepted: 3324 Descri ...

  6. 洛谷⑨月月赛Round2 P3393逃离僵尸岛[最短路]

    题目描述 小a住的国家被僵尸侵略了!小a打算逃离到该国唯一的国际空港逃出这个国家. 该国有N个城市,城市之间有道路相连.一共有M条双向道路.保证没有自环和重边. K个城市已经被僵尸控制了,如果贸然闯入 ...

  7. 第四章 Hibernate入门

    1.构建了一个Student实体类 public class Student { private Integer id; //name private String name; //age priva ...

  8. javascript一些小问题

    1.async 类型:Boolean 默认值: true.默认设置下,所有请求均为异步请求.如果需要发送同步请求,请将此选项设置为 false. 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完 ...

  9. PAT 1023. 组个最小数 (20)

    给定数字0-9各若干个.你可以以任意顺序排列这些数字,但必须全部使用.目标是使得最后得到的数尽可能小(注意0不能做首位).例如:给定两个0,两个1,三个5,一个8,我们得到的最小的数就是1001555 ...

  10. PAT 1007. 素数对猜想 (20)

    让我们定义 dn 为:dn = pn+1 - pn,其中 pi 是第i个素数.显然有 d1=1 且对于n>1有 dn 是偶数."素数对猜想"认为"存在无穷多对相邻且 ...