上篇文章中已经通过一个简单的HelloWorld程序讲解了Spring boot的基本原理和使用。本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是JdbcTemplate,第二种是JPA,第三种是Mybatis。之前已经提到过,本系列会以一个博客系统作为讲解的基础,所以本文会讲解文章的存储和访问(但不包括文章的详情),因为最终的实现是通过MyBatis来完成的,所以,对于JdbcTemplate和JPA只做简单演示,MyBatis部分会完整实现对文章的增删改查。
一、准备工作
在演示这几种方式之前,需要先准备一些东西。第一个就是数据库,本系统是采用MySQL实现的,我们需要先创建一个tb_article的表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
DROP TABLE IF EXISTS `tb_article`; CREATE TABLE `tb_article` ( `id` bigint (20) NOT NULL AUTO_INCREMENT, `title` varchar (255) NOT NULL DEFAULT '' , `summary` varchar (1024) NOT NULL DEFAULT '' , `status` int (11) NOT NULL DEFAULT '0' , `type` int (11) NOT NULL , `user_id` bigint (20) NOT NULL DEFAULT '0' , `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP , `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP , `public_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
后续的演示会对这个表进行增删改查,大家应该会看到这个表里面并没有文章的详情,原因是文章的详情比较长,如果放在这个表里面容易影响查询文章列表的效率,所以文章的详情会单独存在另外的表里面。此外我们需要配置数据库连接池,这里我们使用druid连接池,另外配置文件使用yaml配置,即application.yml(你也可以使用application.properties配置文件,没什么太大的区别,如果对ymal不熟悉,有兴趣也可以查一下,比较简单)。连接池的配置如下:
1
2
3
4
5
6
7
|
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/blog?useUnicode=true&characterEncoding=UTF-8&useSSL=false driverClassName: com.mysql.jdbc.Driver username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource |
最后,我们还需要建立与数据库对应的POJO类,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Article { private Long id; private String title; private String summary; private Date createTime; private Date publicTime; private Date updateTime; private Long userId; private Integer status; private Integer type; } |
好了,需要准备的工作就这些,现在开始实现数据库的操作。
二、与JdbcTemplate集成
首先,我们先通过JdbcTemplate来访问数据库,这里只演示数据的插入,上一篇文章中我们已经提到过,Spring boot提供了许多的starter来支撑不同的功能,要支持JdbcTemplate我们只需要引入下面的starter就可以了:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-jdbc</ artifactId > </ dependency > |
现在我们就可以通过JdbcTemplate来实现数据的插入了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public interface ArticleDao { Long insertArticle(Article article); } @Repository public class ArticleDaoJdbcTemplateImpl implements ArticleDao { @Autowired private NamedParameterJdbcTemplate jdbcTemplate; @Override public Long insertArticle(Article article) { String sql = "insert into tb_article(title,summary,user_id,create_time,public_time,update_time,status) " + "values(:title,:summary,:userId,:createTime,:publicTime,:updateTime,:status)" ; Map<String, Object> param = new HashMap<>(); param.put( "title" , article.getTitle()); param.put( "summary" , article.getSummary()); param.put( "userId" , article.getUserId()); param.put( "status" , article.getStatus()); param.put( "createTime" , article.getCreateTime()); param.put( "publicTime" , article.getPublicTime()); param.put( "updateTime" , article.getUpdateTime()); return ( long ) jdbcTemplate.update(sql, param); } } |
我们通过JUnit来测试上面的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@RunWith (SpringJUnit4ClassRunner. class ) @SpringBootTest (classes = Application. class ) public class ArticleDaoTest { @Autowired private ArticleDao articleDao; @Test public void testInsert() { Article article = new Article(); article.setTitle( "测试标题" ); article.setSummary( "测试摘要" ); article.setUserId(1L); article.setStatus( 1 ); article.setCreateTime( new Date()); article.setUpdateTime( new Date()); article.setPublicTime( new Date()); articleDao.insertArticle(article); } } |
要支持上面的测试程序,也需要引入一个starter:
1
2
3
4
5
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-test</ artifactId > < scope >test</ scope > </ dependency > |
从上面的代码可以看出,其实除了引入jdbc的start之外,基本没有配置,这都是spring boot的自动帮我们完成了配置的过程。上面的代码需要注意的Application类的位置,该类必须位于Dao类的父级的包中,比如这里Dao都位于com.pandy.blog.dao这个包下,现在我们把Application.java这个类从com.pandy.blog这个包移动到com.pandy.blog.app这个包中,则会出现如下错误:
1
2
3
4
5
6
|
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pandy.blog.dao.ArticleDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 28 more |
也就是说,找不到ArticleDao的实现,这是什么原因呢?上一篇博文中我们已经看到@SpringBootApplication这个注解继承了@ComponentScan,其默认情况下只会扫描Application类所在的包及子包。因此,对于上面的错误,除了保持Application类在Dao的父包这种方式外,也可以指定扫描的包来解决:
1
2
3
4
5
6
7
|
@SpringBootApplication @ComponentScan ({ "com.pandy.blog" }) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application. class , args); } } |
三、与JPA集成
现在我们开始讲解如何通过JPA的方式来实现数据库的操作。还是跟JdbcTemplate类似,首先,我们需要引入对应的starter:
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > |
然后我们需要对POJO类增加Entity的注解,并指定表名(如果不指定,默认的表名为article),然后需要指定ID的及其生成策略,这些都是JPA的知识,与Spring boot无关,如果不熟悉的话可以看下JPA的知识点:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Entity (name = "tb_article" ) public class Article { @Id @GeneratedValue private Long id; private String title; private String summary; private Date createTime; private Date publicTime; private Date updateTime; private Long userId; private Integer status; } |
最后,我们需要继承JpaRepository这个类,这里我们实现了两个查询方法,第一个是符合JPA命名规范的查询,JPA会自动帮我们完成查询语句的生成,另一种方式是我们自己实现JPQL(JPA支持的一种类SQL的查询)。
1
2
3
4
5
|
public interface ArticleRepository extends JpaRepository<Article, Long> { public List<Article> findByUserId(Long userId); @Query ( "select art from com.pandy.blog.po.Article art where id="codetool">
|