Springboot中使用Spring-data-jpa方便快捷的訪問數(shù)據(jù)庫(推薦)

什么是JPA

晉寧ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!

JPA(Java Persistence API)是Sun官方提出的Java持久化規(guī)范。它為Java開發(fā)人員提供了一種對(duì)象/關(guān)聯(lián)映射工具來管理Java應(yīng)用中的關(guān)系數(shù)據(jù)。他的出現(xiàn)主要是為了簡化現(xiàn)有的持久化開發(fā)工作和整合ORM技術(shù)

Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規(guī)范的基礎(chǔ)上封裝的一套JPA應(yīng)用框架,可使開發(fā)者用極簡的代碼即可實(shí)現(xiàn)對(duì)數(shù)據(jù)的訪問和操作。它提供了包括增刪改查等在內(nèi)的常用功能,且易于擴(kuò)展!學(xué)習(xí)并使用 Spring Data JPA 可以極大提高開發(fā)效率!

Spring Boot中使用JdbcTemplate訪問數(shù)據(jù)庫

數(shù)據(jù)源配置

首先,為了連接數(shù)據(jù)庫需要引入jdbc支持,在pom.xml中引入如下配置

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

嵌入式數(shù)據(jù)庫支持

嵌入式數(shù)據(jù)庫通常用于開發(fā)和測(cè)試環(huán)境。Spring-Boot提供自動(dòng)配置的嵌入式數(shù)據(jù)庫有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。

如h3的依賴

<dependency>
 <groupId>com.h3database</groupId>
 <artifactId>h3</artifactId>
 <scope>runtime</scope>
</dependency>

MySQL數(shù)據(jù)庫支持

<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.38</version>
</dependency>

編輯配置信息

在 src/main/resources/application.properties 中配置數(shù)據(jù)源信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

使用JdbcTemplate操作數(shù)據(jù)庫

Spring的JdbcTemplate是自動(dòng)配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。

通過JdbcTemplate實(shí)現(xiàn)DemoService中定義的數(shù)據(jù)訪問操作

@Service
public class DemoSerivce {
 @Autowired
 private JdbcTemplate jdbcTemplate;
 public void create(String name, Integer age) {
  jdbcTemplate.update("insert into DEMO(NAME, AGE) values(?, ?)", name, age);
 }
 public void deleteByName(String name) {
  jdbcTemplate.update("delete from DEMOwhere NAME = ?", name);
 }
 public Integer getAllDemo() {
  return jdbcTemplate.queryForObject("select count(1) from DEMO", Integer.class);
 }
 public void deleteAllDemo() {
  jdbcTemplate.update("delete from DEMO");
 }
}

創(chuàng)建對(duì)UserService的單元測(cè)試用例,通過創(chuàng)建、刪除和查詢來驗(yàn)證數(shù)據(jù)庫操作的正確性。

測(cè)試用例要增加依賴

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

測(cè)試代碼

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Main.class)
public class ApplicationTests {
 @Autowired
 private DemoSerivce demoSerivce;
 @Before
 public void setUp() {
 // 準(zhǔn)備,清空表
 demoSerivce.deleteAllDemo();
 }
 @Test
 public void test() throws Exception {
 // 插入5個(gè)
 demoSerivce.create("a", 1);
 demoSerivce.create("b", 2);
 demoSerivce.create("c", 3);
 demoSerivce.create("d", 4);
 demoSerivce.create("e", 5);
 Assert.assertEquals(5, demoSerivce.getAllDemo().intValue());
 demoSerivce.deleteByName("a");
 demoSerivce.deleteByName("e");
 // 查數(shù)據(jù)庫,應(yīng)該有5個(gè)
 Assert.assertEquals(3, demoSerivce.getAllDemo().intValue());
 }
}

Spring Boot中使用Spring-data-jpa

為了解決這些大量枯燥的數(shù)據(jù)操作語句,我們第一個(gè)想到的是使用ORM框架,比如:Hibernate。通過整合Hibernate之后,我們以操作Java實(shí)體的方式最終將數(shù)據(jù)改變映射到數(shù)據(jù)庫表中。

為了解決抽象各個(gè)Java實(shí)體基本的“增刪改查”操作,我們通常會(huì)以泛型的方式封裝一個(gè)模板Dao來進(jìn)行抽象簡化,但是這樣依然不是很方便,我們需要針對(duì)每個(gè)實(shí)體編寫一個(gè)繼承自泛型模板Dao的接口,再編寫該接口的實(shí)現(xiàn)。雖然一些基礎(chǔ)的數(shù)據(jù)訪問已經(jīng)可以得到很好的復(fù)用,但是在代碼結(jié)構(gòu)上針對(duì)每個(gè)實(shí)體都會(huì)有一堆Dao的接口和實(shí)現(xiàn)。

由于模板Dao的實(shí)現(xiàn),使得這些具體實(shí)體的Dao層已經(jīng)變的非?!氨 ?,有一些具體實(shí)體的Dao實(shí)現(xiàn)可能完全就是對(duì)模板Dao的簡單代理,并且往往這樣的實(shí)現(xiàn)類可能會(huì)出現(xiàn)在很多實(shí)體上。Spring-data-jpa的出現(xiàn)正可以讓這樣一個(gè)已經(jīng)很“薄”的數(shù)據(jù)訪問層變成只是一層接口的編寫方式。

使用方法

添加依賴

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

編輯配置信息

在 src/main/resources/application.properties 中配置數(shù)據(jù)源信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置屬性,其主要作用是:自動(dòng)創(chuàng)建、更新、驗(yàn)證數(shù)據(jù)庫表結(jié)構(gòu)。該參數(shù)的幾種配置如下

  • create: 每次加載hibernate時(shí)都會(huì)刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表
  • create-drop:每次加載hibernate時(shí)根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動(dòng)刪除
  • update:最常用的屬性,第一次加載hibernate時(shí)根據(jù)model類會(huì)自動(dòng)建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載hibernate時(shí)根據(jù)model類自動(dòng)更新表結(jié)構(gòu)
  • validate:每次加載hibernate時(shí),驗(yàn)證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會(huì)和數(shù)據(jù)庫中的表進(jìn)行比較,不會(huì)創(chuàng)建新表,但是會(huì)插入新值

創(chuàng)建實(shí)體

@Entity
public class DemoEntity {
 @Id
 @GeneratedValue
 private long id;
 private String title;
 private String content;
 public DemoEntity() {
 }
 public DemoEntity(String title, String content) {
 this.title = title;
 this.content = content;
 }
 // get set 略
}

創(chuàng)建DAO

public interface DemoRepository extends JpaRepository<DemoEntity, Long> {
 DemoEntity findByTitle(String title);
 DemoEntity findByTitleAndContent(String title, String content);
// @Query("select u from DemoEntity u where u.content=:content")
 @Query("from DemoEntity u where u.content=:content")
 DemoEntity sqlFind(@Param("content") String content);
}

sql中不要寫表名,要寫實(shí)體名,他會(huì)自動(dòng)轉(zhuǎn)化為表名的。

通過解析方法名創(chuàng)建查詢

上面 findByTitle(String title) 與 findByTitleAndContent(String title, String content) ,沒有寫sql,但框架會(huì)自動(dòng)按名字對(duì)上面的方對(duì)創(chuàng)建sql。

單元測(cè)試

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Main.class)
public class UnitTest {
 @Autowired
 DemoRepository demoRepository;
 @Test
 public void test()
 {
 for(int i=0;i<10;i++)
 {
 demoRepository.save(new DemoEntity("title"+i, "content"+i));
 }
 Assert.assertEquals(10, demoRepository.findAll().size());
 }
 @Test
 public void testfindbytitle()
 {
 DemoEntity res = demoRepository.findByTitle("title8");
 Assert.assertEquals("title8", res.getTitle());
 }
 @Test
 public void testfindbytitleandcontent()
 {
 DemoEntity res = demoRepository.findByTitleAndContent("title9", "content9");
 Assert.assertEquals("title9", res.getTitle());
 Assert.assertEquals("content9", res.getContent());
 }
 @Test
 public void testsqlFind()
 {
 DemoEntity res = demoRepository.sqlFind("content7");
 Assert.assertEquals("content7", res.getContent());
 }
}

總結(jié)

以上所述是小編給大家介紹的Spring boot中使用Spring-data-jpa方便快捷的訪問數(shù)據(jù)庫,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)創(chuàng)新互聯(lián)網(wǎng)站的支持!

網(wǎng)頁標(biāo)題:Springboot中使用Spring-data-jpa方便快捷的訪問數(shù)據(jù)庫(推薦)
網(wǎng)站路徑:http://bm7419.com/article18/gijpgp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、軟件開發(fā)、Google、網(wǎng)站導(dǎo)航、建站公司、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作