使用数据库是开发应用的基本基础,那么,使用Spring Boot如何连接数据库呢?
前提,需要知道如何建一个Spring Boot项目,可参照:https://www.jianshu.com/p/d6e6c84cd190
作者:莫问以
链接:https://www.jianshu.com/p/414ef5b49a69
来源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
一、准备工作:
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=1DEFAULT 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类,代码如下:
publicclassAuthor{privateLong id;privateString realName;privateString nickName;// SET和GET方法略}
二、方式一:与JdbcTemplate集成
通过JdbcTemplate来访问数据库,Spring boot提供了如下的starter来支撑:
再引入Junit测试Starter:
DAO接口:
packagecom.guxf.dao;importjava.util.List;importcom.guxf.domain.Author;publicinterfaceAuthorDao{intadd(Authorauthor);intupdate(Authorauthor);intdelete(Longid);AuthorfindAuthor(Longid);List
实现Dao接口代码(此处只写Add,其他方法略):
packagecom.guxf.impl;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;importorg.springframework.stereotype.Repository;importcom.guxf.dao.AuthorDao;importcom.guxf.domain.Author;@RepositorypublicclassAuthorDaoJdbcTemplateImplimplementsAuthorDao{@AutowiredprivateNamedParameterJdbcTemplatejdbcTemplate;@Overridepublicintadd(Authorauthor){Stringsql="insert into t_author(id,real_name,nick_name) "+"values(:id,:realName,:nickName)";Map
通过JUnit来测试上面的代码(需根据自己的实际Application名稍作修改):
packagecom.guxf.boot;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importcom.guxf.BootApplication;importcom.guxf.dao.AuthorDao;importcom.guxf.domain.Author;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes=BootApplication.class)publicclassAuthorDaoTest{@AutowiredprivateAuthorDao authorDao;@TestpublicvoidtestInsert(){Author author=newAuthor();author.setId(1L);author.setRealName("莫言");author.setNickName("疯子");authorDao.add(author);System.out.println("插入成功!");}}
插入成功:
成功.png
PS:需要注意的是,Application类所在的包必须是其他包的父包,@SpringBootApplication这个注解继承了@ComponentScan,其默认情况下只会扫描Application类所在的包及子包,结构图:
目录结构图.png
Application代码示例:
packagecom.guxf;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassBootApplication{publicstaticvoidmain(String[]args){SpringApplication.run(BootApplication.class,args);}}
三、方式二:与JPA集成
引入Starter:
对POJO类增加Entity的注解,并指定表名(如果不指定,默认的表名为author),然后指定ID的及其生成策略,这些都是JPA的知识,与Spring boot无关,代码:
packagecom.guxf.domain;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.Id;@Entity(name="t_author")publicclassAuthor{@Id@GeneratedValueprivateLong id;privateString realName;privateString nickName;// SET和GET方法略}
需要继承JpaRepository这个类,这里我们实现了两个查询方法,第一个是符合JPA命名规范的查询,JPA会自动帮我们完成查询语句的生成,另一种方式是我们自己实现JPQL(JPA支持的一种类SQL的查询):
packagecom.guxf.service;importjava.util.List;importjava.util.Optional;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.data.jpa.repository.Query;importorg.springframework.data.repository.query.Param;importcom.guxf.domain.Author;publicinterfaceAuthorRepository extends JpaRepository
测试代码:
package com.guxf.boot;importstaticorg.junit.Assert.*;importjava.util.List;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importcom.guxf.BootApplication;importcom.guxf.domain.Author;importcom.guxf.service.AuthorRepository;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes=BootApplication.class)publicclassAuthorDaoTestJPA{@AutowiredprivateAuthorRepositoryauthorRepository;@TestpublicvoidtestQuery(){List
四、方式三:与MyBatis集成
引入starter:
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.DruidDataSourcemybatis: #config-locations: mybatis/mybatis-config.xml mapper-locations: com/guxf/mapper/*.xml type-aliases-package: com.guxf.mapper.AuthorMapper
编写mapper对应的接口:
packagecom.guxf.mapper;importorg.apache.ibatis.annotations.Mapper;importcom.baomidou.mybatisplus.mapper.BaseMapper;importcom.guxf.domain.Author;@MapperpublicinterfaceAuthorMapperextendsBaseMapper
配置Mapper的XML文件:
测试类代码:
packagecom.guxf;importstaticorg.junit.Assert.*;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importcom.guxf.BootApplication;importcom.guxf.domain.Author;importcom.guxf.mapper.AuthorMapper;@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes=BootApplication.class)publicclassAuthorDaoTestMybatis{@AutowiredprivateAuthorMappermapper;@TestpublicvoidtestInsert(){Authorauthor=newAuthor();author.setId(4L);author.setRealName("唐钰");author.setNickName("小宝");mapper.insertAuthor(author);System.out.println("成功!");}@TestpublicvoidtestMybatisQuery(){Authorauthor=mapper.queryById(1L);assertNotNull(author);System.out.println(author);}@TestpublicvoidtestUpdate(){Authorauthor=mapper.queryById(2L);author.setNickName("月儿");author.setRealName("林月如");mapper.updateAuthor(author);}}
我们看测试结果:
测试结果.png
配置扫描,需要根据自己项目结构实际修改,下面贴上我的项目结构图:
结构.png
作者:莫问以
链接:https://www.jianshu.com/p/414ef5b49a69
来源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。