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/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-idle=10spring.datasource.max-wait=1000spring.datasource.min-idle=5spring.datasource.initial-size=5server.port=8012server.session.timeout=10server.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/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-idle=10spring.datasource.max-wait=1000spring.datasource.min-idle=5spring.datasource.initial-size=5server.port=8012server.session.timeout=10server.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;@Servicepublic 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启动类必须要保证在包的根目录下。

SpringBoot建立数据库连接JdbcTemplate和Mybatis两种方式相关推荐

  1. springboot配置多个数据源(两种方式)

    在我们的实际业务中可能会遇到:在一个项目里面读取多个数据库的数据来进行展示,spring对同时配置多个数据源是支持的. 本文中将展示两种方法来实现这个功能. springboot+mybatis 第一 ...

  2. Spring-boot中读取config配置文件的两种方式

    了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息. Spring-Boot读取配 ...

  3. Springboot pox.xml 报错解决两种方式

    首次运用spring boot,然后细心的学习了一天,每一个系统在没有全部弄清它之前.里面的各种配置,运行时总会出现想不到的意外. 总结一天学习的结果:程序正常运行.明白里面的原理.返回json和返回 ...

  4. Springboot之返回json数据格式的两种方式-yellowcong

    SpringBoot返回字符串的方式也是有两种,一种是通过@ResponseBody 和@RequestMapping(value = "/request/data", metho ...

  5. springboot java8使用jacob,aspose两种方式实现excel、word转pdf

    其实还有一种spire转化PDF,不过这种是收费的还有限制只能导出3个sheet页数据也有限制 1.使用jacob 1.1引入依赖 <!--jacob依赖--><dependency ...

  6. SpringBoot 使用ApplicationContext 及 getbean的两种方式

    第一种:容器加载时设置 public class ProxyApplication {public static void main(String[] args) {ApplicationContex ...

  7. hive建立内部表映射hbase_Hive 建外链表到 Hbase(分内部表、外部表两种方式)

    一. Hive 建内部表,链到hbase :特点:Hive drop表后,Hbase 表同步删除 drop table if exists hbase_kimbo_test1; CREATE TABL ...

  8. springboot项目中利用@WebFilter注解和@Bean配置类两种方式实现Filter过滤器

    过滤器(Filter) 过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理.通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理 ...

  9. SpringBoot实现多数据源的两种方式

    前言 公司项目有连接多个不同数据库的需求,特研究了一下,根据网上的资料,造了一个基于AOP方式的数据源切换轮子,但继续探索,突然发现有开源的多数据源管理启动器.不过,本篇两种方式都会介绍. 基于dyn ...

  10. php+mysqli,php+mysqli数据库连接的两种方式

    这篇文章主要介绍了php+mysqli数据库连接的两种方式,实例分析了面向对象与面向过程两种连接方式,非常具有实用价值,需要的朋友可以参考下 本文实例讲述了php+mysqli数据库连接的两种方式.分 ...

最新文章

  1. BasicModal - 简单易用的现代 Web App 弹窗
  2. AI实验室•西安站 教你用人脸识别打造爆款应用
  3. python 的文件目录拷贝转移,自动递归目录建立目录
  4. 从测试的角度来重新反思我们自己的程序以及我们的程序员之路——“通过追本溯源来进行前瞻性思考”...
  5. Java复制目录/子目录/文件
  6. smarty能创建 php页面,php+smarty生成静态页面详解
  7. JAVA复习5(集合——集合的遍历 Iteratorforeach、Enumeration——HashMap、HashTable、LinkedHashMap——map的遍历)
  8. 串行线路上传输数据报的非标准协议:SLIP
  9. framebuffer驱动详解2——framebuffer驱动框架分析
  10. 爬虫技术前置准备工作 http url 请求方法 状态码 等等
  11. C#/java 求最大公约数和最小公倍数
  12. 6-Arco大讲堂(一)
  13. android (12) Fragment使用
  14. AR 圈最大收购案 Ubimax 10 亿“卖身”背后:究竟什么才是真正值钱的东西?
  15. Android OpenGL 使用
  16. mysql get global_getdata table表格数据join mysql方法
  17. MyBatis架构图
  18. 将SpringBoot项目打包并部署到服务器
  19. Sphinx速成指南
  20. 获取高德地图省市区县列表

热门文章

  1. 开发问题及解决 java.lang.ClassCastException:android.widget.LinearLayout$LayoutParams
  2. Linux常用基本命令及应用技巧1
  3. 序列化之Java默认序列化技术(ObjectOutputStream与ObjectInputStream)
  4. 函数响应式编程及ReactiveObjC学习笔记 (三)
  5. 物联网领域不断扩展,ATT很“兴奋”
  6. 微软Azure、谷歌GAE、亚马逊AWS比較
  7. asp.net core web api token验证和RestSharp访问
  8. iOS开发UIScrollView使用详解
  9. OpenStack单点部署及使用简单教程(附:部署好的VMware虚拟机)
  10. hibernate----继承