上篇文章中已經經過一個簡單的HelloWorld程序講解了Spring boot的基本原理和使用。本文主要講解如何經過spring boot來訪問數據庫,本文會演示三種方式來訪問數據庫,第一種是JdbcTemplate,第二種是JPA,第三種是Mybatis。以前已經提到過,本系列會以一個博客系統做爲講解的基礎,因此本文會講解文章的存儲和訪問(但不包括文章的詳情),由於最終的實現是經過MyBatis來完成的,因此,對於JdbcTemplate和JPA只作簡單演示,MyBatis部分會完整實現對文章的增刪改查。java
1、準備工做mysql
在演示這幾種方式以前,須要先準備一些東西。第一個就是數據庫,本系統是採用MySQL實現的,咱們須要先建立一個tb_article的表:spring
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不熟悉,有興趣也能夠查一下,比較簡單)。鏈接池的配置以下:sql
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類,代碼以下:數據庫
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;
}
好了,須要準備的工做就這些,如今開始實現數據庫的操做。mybatis
2、與JdbcTemplate集成app
首先,咱們先經過JdbcTemplate來訪問數據庫,這裏只演示數據的插入,上一篇文章中咱們已經提到過,Spring boot提供了許多的starter來支撐不一樣的功能,要支持JdbcTemplate咱們只須要引入下面的starter就能夠了:ide
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
如今咱們就能夠經過JdbcTemplate來實現數據的插入了:spring-boot
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來測試上面的代碼:測試
@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:
<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這個包中,則會出現以下錯誤:
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的父包這種方式外,也能夠指定掃描的包來解決:
@SpringBootApplication @ComponentScan({"com.pandy.blog"}) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
3、與JPA集成
如今咱們開始講解如何經過JPA的方式來實現數據庫的操做。仍是跟JdbcTemplate相似,首先,咱們須要引入對應的starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
而後咱們須要對POJO類增長Entity的註解,並指定表名(若是不指定,默認的表名爲article),而後須要指定ID的及其生成策略,這些都是JPA的知識,與Spring boot無關,若是不熟悉的話能夠看下JPA的知識點:
@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的查詢)。
public interface ArticleRepository extends JpaRepository<Article, Long> { public List<Article> findByUserId(Long userId); @Query("select art from com.pandy.blog.po.Article art where title=:title") public List<Article> queryByTitle(@Param("title") String title); }
好了,咱們能夠再測試一下上面的代碼:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) public class ArticleRepositoryTest { @Autowired private ArticleRepository articleRepository; @Test public void testQuery(){ List<Article> articleList = articleRepository.queryByTitle("測試標題"); assertTrue(articleList.size()>0); } }
注意,這裏仍是存在跟JdbcTemplate相似的問題,須要將Application這個啓動類未於Respository和Entity類的父級包中,不然會出現以下錯誤:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pandy.blog.dao.ArticleRepository' 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
固然,一樣也能夠經過註解@EnableJpaRepositories指定掃描的JPA的包,可是仍是不行,還會出現以下錯誤:
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.pandy.blog.po.Article at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210) at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70) at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82) at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ... 39 more
這個錯誤說明識別不了Entity,因此還須要經過註解@EntityScan來指定Entity的包,最終的配置以下:
@SpringBootApplication @ComponentScan({"com.pandy.blog"}) @EnableJpaRepositories(basePackages="com.pandy.blog") @EntityScan("com.pandy.blog") public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
4、與MyBatis集成
最後,咱們再看看如何經過MyBatis來實現數據庫的訪問。一樣咱們仍是要引入starter:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
因爲該starter不是spring boot官方提供的,因此版本號於Spring boot不一致,須要手動指定。
MyBatis通常能夠經過XML或者註解的方式來指定操做數據庫的SQL,我的比較偏向於XML,因此,本文中也只演示了經過XML的方式來訪問數據庫。首先,咱們須要配置mapper的目錄。咱們在application.yml中進行配置:
mybatis: config-locations: mybatis/mybatis-config.xml mapper-locations: mybatis/mapper/*.xml type-aliases-package: com.pandy.blog.po
這裏配置主要包括三個部分,一個是mybatis自身的一些配置,例如基本類型的別名。第二個是指定mapper文件的位置,第三個POJO類的別名。這個配置也能夠經過 Java configuration來實現,因爲篇幅的問題,我這裏就不詳述了,有興趣的朋友能夠本身實現一下。
配置完後,咱們先編寫mapper對應的接口:
public interface ArticleMapper { public Long insertArticle(Article article); public void updateArticle(Article article); public Article queryById(Long id); public List<Article> queryArticlesByPage(@Param("article") Article article, @Param("pageSize") int pageSize, @Param("offset") int offset); }
該接口暫時只定義了四個方法,即添加、更新,以及根據ID查詢和分頁查詢。這是一個接口,而且和JPA相似,能夠不用實現類。接下來咱們編寫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.pandy.blog.dao.ArticleMapper"> <resultMap id="articleMap" type="com.pandy.blog.po.Article"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="title" property="title" jdbcType="VARCHAR"/> <result column="summary" property="summary" jdbcType="VARCHAR"/> <result column="user_id" property="userId" jdbcType="INTEGER"/> <result column="status" property="status" jdbcType="INTEGER"/> <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/> <result column="public_time" property="publicTime" jdbcType="TIMESTAMP"/> </resultMap> <sql id="base_column"> title,summary,user_id,status,create_time,update_time,public_time </sql> <insert id="insertArticle" parameterType="Article"> INSERT INTO tb_article(<include refid="base_column"/>) VALUE (#{title},#{summary},#{userId},#{status},#{createTime},#{updateTime},#{publicTime}) </insert> <update id="updateArticle" parameterType="Article"> UPDATE tb_article <set> <if test="title != null"> title = #{title}, </if> <if test="summary != null"> summary = #{summary}, </if> <if test="status!=null"> status = #{status}, </if> <if test="publicTime !=null "> public_time = #{publicTime}, </if> <if test="updateTime !=null "> update_time = #{updateTime}, </if> </set> WHERE id = #{id} </update> <select id="queryById" parameterType="Long" resultMap="articleMap"> SELECT id,<include refid="base_column"></include> FROM tb_article WHERE id = #{id} </select> <select id="queryArticlesByPage" resultMap="articleMap"> SELECT id,<include refid="base_column"></include> FROM tb_article <where> <if test="article.title != null"> title like CONCAT('%',${article.title},'%') </if> <if test="article.userId != null"> user_id = #{article.userId} </if> </where> limit #{offset},#{pageSize} </select> </mapper>
最後,咱們須要手動指定mapper掃描的包:
@SpringBootApplication @MapperScan("com.pandy.blog.dao") public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
好了,與MyBatis的集成也完成了,咱們再測試一下:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) public class ArticleMapperTest { @Autowired private ArticleMapper mapper; @Test public void testInsert() { Article article = new Article(); article.setTitle("測試標題2"); article.setSummary("測試摘要2"); article.setUserId(1L); article.setStatus(1); article.setCreateTime(new Date()); article.setUpdateTime(new Date()); article.setPublicTime(new Date()); mapper.insertArticle(article); } @Test public void testMybatisQuery() { Article article = mapper.queryById(1L); assertNotNull(article); } @Test public void testUpdate() { Article article = mapper.queryById(1L); article.setPublicTime(new Date()); article.setUpdateTime(new Date()); article.setStatus(2); mapper.updateArticle(article); } @Test public void testQueryByPage(){ Article article = new Article(); article.setUserId(1L); List<Article> list = mapper.queryArticlesByPage(article,10,0); assertTrue(list.size()>0); } }
5、總結
本文演示Spring boot與JdbcTemplate、JPA以及MyBatis的集成,總體上來講配置都比較簡單,之前作過相關配置的同窗應該感受比較明顯,Spring boot確實在這方面給咱們提供了很大的幫助。後續的文章中咱們只會使用MyBatis這一種方式來進行數據庫的操做,這裏還有一點須要說明一下的是,MyBatis的分頁查詢在這裏是手寫的,這個分頁在正式開發中能夠經過插件來完成,不過這個與Spring boot沒什麼關係,因此本文暫時經過這種手動的方式來進行分頁的處理。