Spring Boot高级教程之Spring Boot连接MySql数据库

Spring Boot可以大大简化持久化任务,几乎不需要写SQL语句,在之前章节“Spring Boot 构建框架”中我们新建了一个Spring Boot应用程序,本章在原有的工程中与数据库建立连接。

Spring Boot有两种方法与数据库建立连接,一种是使用JdbcTemplate,另一种集成Mybatis,下面分别为大家介绍一下如何集成和使用这两种方式。

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=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

新建Controller类测试数据库连接,实例如下:

package com.example.demo;
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;
  }

}

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

2. 集成Mybatis

添加mybatis依赖,在pom.xml文件中增加如下:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</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=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

依次添加mapper的接口类和xml文件,类分别如下:
AppMessageMapper.java

package com.example.demo.mapper;
import java.util.List;
import com.example.demo.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.xml

<?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.example.demo.mapper.AppMessageMapper" >
 <resultMap id="BaseResultMap" type="com.example.demo.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.example.demo.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.example.demo.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.example.demo.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.example.demo.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>

AppMessage.java

package com.example.demo.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;
  }
}

AppMessageService.java

package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.bean.AppMessage;
import com.example.demo.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);
  }
}

APPMessageController.java

package com.example.demo.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.example.demo.bean.AppMessage;
import com.example.demo.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)

  // 或者采用@PostMapping("/add")方法,更加节省代码的编写量
  public int addMessage(@RequestBody AppMessage appMessage){
    return service.addMessage(appMessage);
  }

  @RequestMapping(value="/delMessageById",method=RequestMethod.POST) 

  // 或者采用@PostMapping("/delMessageById")方法,更加节省代码的编写量
  public int delMessageById(@RequestParam("id") String id){
      return service.delMessage(id);
  }
}

问题描述?

SpringBoot扫描包提示找不到mapper的问题,异常信息:
Consider defining a bean of type in your configuration

分析原因

Spring Boot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描,“Application类”是指Spring Boot项目入口类。如果Application类所在的包为:com.yoodb.blog,则只会扫描com.yoodb.blog包及其所有子包,如果service或dao所在包不在com.yoodb.blog及其子包下,则不会被扫描。

解决方法

方式一:使用注解@ComponentScan(value=”com.yoodb.blog”),其中,com.yoodb.blog为包路径。
方式二:将启动类Application放在上一级包中,注意的是Application启动类必须要保证在包的根目录下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot用JdbcTemplates访问Mysql实例代码

    本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: -- create table `account` DROP TABLE `account` IF EXISTS CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL,

  • SpringBoot连接MYSQL数据库并使用JPA进行操作

    今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作. 步骤一:在pom.xml文件中添加MYSQl和JPA的相关Jar包依赖,具体添加位置在dependencies中,具体添加的内容如下所示. <!--数据库相关配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-

  • Spring Boot如何解决Mysql断连问题

    在Spring Boot JPA连接Mysql的过程中,经过 8小时后会发现断连的情况.application.properties配置如下(此坑我跳过,欢迎入坑): spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jd

  • 详解在Spring Boot中使用Mysql和JPA

    本文向你展示如何在Spring Boot的Web应用中使用Mysq数据库,也充分展示Spring Boot的优势(尽可能少的代码和配置).数据访问层我们将使用Spring Data JPA和Hibernate(JPA的实现之一). 1.Maven pom.xml文件 在你的项目中增加如下依赖文件 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifa

  • Spring Boot Mysql 数据库操作示例

    本文默认你的开发环境.数据库已经安装好 想用使用数据库.我们需要现在pom文件中添加相应的依赖 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sc

  • Spring Boot中使用jdbctemplate 操作MYSQL数据库实例

    最近在学习使用Spring Boot连接数据库,今天学习了使用jdbctemplate 操作MYSQL数据库,下面就留个笔记 不废话,先来代码 pom文件: <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

  • Spring Boot 添加MySQL数据库及JPA实例

    最近在学习Spring Boot,继续前面的学习,这一次我们加入MySQL数据库和JPA. 配置: pom.xml文件 <!-- 添加Mysql和JPA--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dep

  • SpringBoot入门系列之JPA mysql

    一,准备工作,建立spring-boot-sample-mysql工程 1.http://start.spring.io/ A.Artifact中输入spring-boot-sample-MySQL      B.勾选Web下的web      C.勾选SQL下的JPA MYSQL 2.Eclips中导入工程spring-boot-sample-mysql A.解压快捷工程spring-boot-sample-mysql到某文件夹 B.eclips中file->import->Import E

  • Spring Boot JPA访问Mysql示例

    上篇演示了通过Maven构建Spring Boot 项目,引用web模块启动应用,完成简单的web 应用访问,本章内容在此基础上面加入数据访问与端口修改,下文代码与演例(本用例纯手工测试通过,放心入坑). 修改默认端口 在src\main\resources下加入application.properties内容如下 server.port=8888 项目目录结构 启动应用,日志显示: 端口已经由默认的8080 变更为8888 JPA访问mysql数据库 1.POM中加入 <!-- Spring

  • Spring boot 使用mysql实例详解

    Spring boot 使用mysql实例详解 开发阶段用 H2即可,上线时,通过以下配置切换到mysql,spring boot将使用这个配置覆盖默认的H2. 1.建立数据库: mysql -u root CREATE DATABASE springbootdb 2.pom.xml: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId&g

随机推荐