Spring Boot——三种方式连接数据库

使用数据库是开发应用的基本基础,那么,使用Spring Boot如何连接数据库呢?
前提,需要知道如何建一个Spring Boot项目,可参照:https://www.jianshu.com/p/d6e6c84cd190

一、准备工作:

1、建一个简单的数据库,名为springboot_db,在其下建一个表,名为t_author,脚本如下:

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
 
USE `springboot_db`;
 
DROP TABLE IF EXISTS `t_author`;
 
CREATE TABLE `t_author` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2、添加配置文件,可用使用yaml配置,即application.yml(与application.properties配置文件,没什么太大的区别)连接池的配置如下:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/springboot_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

3、需要建立与数据库对应的POJO类,代码如下:

public class Author {
    private Long id;
    private String realName;
    private String nickName;

    // SET和GET方法略
}

二、方式一:与JdbcTemplate集成

通过JdbcTemplate来访问数据库,Spring boot提供了如下的starter来支撑:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

再引入Junit测试Starter:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-test</artifactId>
       <scope>test</scope>
</dependency>

DAO接口:

package com.guxf.dao;

import java.util.List;

import com.guxf.domain.Author;

public interface AuthorDao {

    int add(Author author);

    int update(Author author);

    int delete(Long id);

    Author findAuthor(Long id);

    List<Author> findAuthorList();
}

实现Dao接口代码(此处只写Add,其他方法略):

package com.guxf.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.guxf.dao.AuthorDao;
import com.guxf.domain.Author;

@Repository
public class AuthorDaoJdbcTemplateImpl implements AuthorDao{
    
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    
    @Override
    public int add(Author author) {
        String sql = "insert into t_author(id,real_name,nick_name) " +
                "values(:id,:realName,:nickName)";
        Map<String, Object> param = new HashMap<>();
        param.put("id",author.getId());
        param.put("realName", author.getRealName());
        param.put("nickName", author.getNickName());
        
        return (int) jdbcTemplate.update(sql, param);
    }

    @Override
    public int update(Author author) {  
        return 0;
    }

    @Override
    public int delete(Long id) {    
        return 0;
    }

    @Override
    public Author findAuthor(Long id) {
        return null;
    }

    @Override
    public List<Author> findAuthorList() {  
          return null;
    }
}

通过JUnit来测试上面的代码(需根据自己的实际Application名稍作修改):

package com.guxf.boot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.guxf.BootApplication;
import com.guxf.dao.AuthorDao;
import com.guxf.domain.Author;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BootApplication.class)
public class AuthorDaoTest {

    @Autowired
    private AuthorDao authorDao;

    @Test
    public void testInsert() {
        Author author = new Author();
        author.setId(1L);
        author.setRealName("莫言");
        author.setNickName("疯子");
        
        authorDao.add(author);
        System.out.println("插入成功!");
    }
}

插入成功:


成功.png

PS:需要注意的是,Application类所在的包必须是其他包的父包,@SpringBootApplication这个注解继承了@ComponentScan,其默认情况下只会扫描Application类所在的包及子包,结构图:


目录结构图.png

Application代码示例:
package com.guxf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BootApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }
}

三、方式二:与JPA集成

引入Starter:

<!-- 引入JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

对POJO类增加Entity的注解,并指定表名(如果不指定,默认的表名为author),然后指定ID的及其生成策略,这些都是JPA的知识,与Spring boot无关,代码:

package com.guxf.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity(name = "t_author")
public class Author {
    @Id
    @GeneratedValue
    private Long id;
    private String realName;
    private String nickName;

    // SET和GET方法略
}

需要继承JpaRepository这个类,这里我们实现了两个查询方法,第一个是符合JPA命名规范的查询,JPA会自动帮我们完成查询语句的生成,另一种方式是我们自己实现JPQL(JPA支持的一种类SQL的查询):

package com.guxf.service;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.guxf.domain.Author;

public interface AuthorRepository extends JpaRepository<Author, Long> {

    public Optional<Author> findById(Long userId);

    @Query("select au from com.guxf.domain.Author au where nick_name=:nickName")
    public List<Author> queryByNickName(@Param("nickName") String nickName);
}

测试代码:

package com.guxf.boot;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.guxf.BootApplication;
import com.guxf.domain.Author;
import com.guxf.service.AuthorRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BootApplication.class)
public class AuthorDaoTestJPA {

    @Autowired
    private AuthorRepository authorRepository;

    @Test
    public void testQuery() {
        List<Author> authorList = authorRepository.queryByNickName("疯子");
        assertTrue(authorList.size() > 0);
        System.out.println("成功!");
    }
}

四、方式三:与MyBatis集成

引入starter:

<!-- 引入Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

MyBatis一般可以通过XML或者注解的方式来指定操作数据库的SQL,首先,我们需要配置mapper的目录。我们在application.yml中进行配置:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/springboot_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    driverClassName: com.mysql.jdbc.Driver
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

mybatis:
  #config-locations: mybatis/mybatis-config.xml
  mapper-locations: com/guxf/mapper/*.xml
  type-aliases-package: com.guxf.mapper.AuthorMapper

编写mapper对应的接口:

package com.guxf.mapper;

import org.apache.ibatis.annotations.Mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.guxf.domain.Author;
@Mapper
public interface AuthorMapper extends BaseMapper<Author> {

    public Long insertAuthor(Author author);

    public void updateAuthor(Author author);

    public Author queryById(Long id);
}

配置Mapper的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.guxf.mapper.AuthorMapper">
    <!-- 此处需要注意的是,由于我们数据库定义的id存储类型为intbig,但是我们的Entity中Id是Long -->
    <!-- 前面的两种方式插入没问题,此处报了数据库类型异常 -->
    <!-- 所以数据库的ID类型改为了Varchar -->
    <resultMap id="authorMap" type="com.guxf.domain.Author">
        <id column="id" property="id" jdbcType="VARCHAR" />
        <result column="real_name" property="realName" jdbcType="VARCHAR" />
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="base_column">
        id,real_name,nick_name
    </sql>

    <insert id="insertAuthor" parameterType="com.guxf.domain.Author">
        INSERT INTO
        t_author(
        <include refid="base_column" />
        )
        VALUE
        (#{id},#{realName},#{nickName})
    </insert>

    <update id="updateAuthor" parameterType="com.guxf.domain.Author">
        UPDATE t_author
        <set>
            <if test="realName != null">
                real_name = #{realName},
            </if>
            <if test="nickName != null">
                nick_name = #{nickName},
            </if>
        </set>
        WHERE id = #{id}
    </update>

    <select id="queryById" parameterType="Long" resultMap="authorMap">
        SELECT id,
        <include refid="base_column"></include>
        FROM t_author
        WHERE id = #{id}
    </select>

</mapper>

测试类代码:

package com.guxf;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.guxf.BootApplication;
import com.guxf.domain.Author;
import com.guxf.mapper.AuthorMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BootApplication.class)
public class AuthorDaoTestMybatis {

    @Autowired
    private AuthorMapper mapper;

    @Test
    public void testInsert() {
        Author author = new Author();
        author.setId(4L);
        author.setRealName("唐钰");
        author.setNickName("小宝");
        mapper.insertAuthor(author);
        System.out.println("成功!");
    }

    @Test
    public void testMybatisQuery() {
        Author author = mapper.queryById(1L);
        assertNotNull(author);
        System.out.println(author);
    }

    @Test
    public void testUpdate() {
        Author author = mapper.queryById(2L);
        author.setNickName("月儿");
        author.setRealName("林月如");
        mapper.updateAuthor(author);
    }
}

我们看测试结果:


测试结果.png

配置扫描,需要根据自己项目结构实际修改,下面贴上我的项目结构图:


结构.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容