Spring boot中使用Spring-data-jpa方便快捷的訪問數(shù)據(jù)庫(推薦)
什么是JPA
JPA(Java Persistence API)是Sun官方提出的Java持久化規(guī)范。它為Java開發(fā)人員提供了一種對象/關(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ā)者用極簡的代碼即可實現(xiàn)對數(shù)據(jù)的訪問和操作。它提供了包括增刪改查等在內(nèi)的常用功能,且易于擴展!學(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ā)和測試環(huán)境。Spring-Boot提供自動配置的嵌入式數(shù)據(jù)庫有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。
如h2的依賴
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</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是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。
通過JdbcTemplate實現(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)建對UserService的單元測試用例,通過創(chuàng)建、刪除和查詢來驗證數(shù)據(jù)庫操作的正確性。
測試用例要增加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
測試代碼
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Main.class)
public class ApplicationTests {
@Autowired
private DemoSerivce demoSerivce;
@Before
public void setUp() {
// 準備,清空表
demoSerivce.deleteAllDemo();
}
@Test
public void test() throws Exception {
// 插入5個
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個
Assert.assertEquals(3, demoSerivce.getAllDemo().intValue());
}
}
Spring Boot中使用Spring-data-jpa
為了解決這些大量枯燥的數(shù)據(jù)操作語句,我們第一個想到的是使用ORM框架,比如:Hibernate。通過整合Hibernate之后,我們以操作Java實體的方式最終將數(shù)據(jù)改變映射到數(shù)據(jù)庫表中。
為了解決抽象各個Java實體基本的“增刪改查”操作,我們通常會以泛型的方式封裝一個模板Dao來進行抽象簡化,但是這樣依然不是很方便,我們需要針對每個實體編寫一個繼承自泛型模板Dao的接口,再編寫該接口的實現(xiàn)。雖然一些基礎(chǔ)的數(shù)據(jù)訪問已經(jīng)可以得到很好的復(fù)用,但是在代碼結(jié)構(gòu)上針對每個實體都會有一堆Dao的接口和實現(xiàn)。
由于模板Dao的實現(xiàn),使得這些具體實體的Dao層已經(jīng)變的非?!氨 ?,有一些具體實體的Dao實現(xiàn)可能完全就是對模板Dao的簡單代理,并且往往這樣的實現(xiàn)類可能會出現(xiàn)在很多實體上。Spring-data-jpa的出現(xiàn)正可以讓這樣一個已經(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的配置屬性,其主要作用是:自動創(chuàng)建、更新、驗證數(shù)據(jù)庫表結(jié)構(gòu)。該參數(shù)的幾種配置如下
- create: 每次加載hibernate時都會刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表
- create-drop:每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動刪除
- update:最常用的屬性,第一次加載hibernate時根據(jù)model類會自動建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載hibernate時根據(jù)model類自動更新表結(jié)構(gòu)
- validate:每次加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會和數(shù)據(jù)庫中的表進行比較,不會創(chuàng)建新表,但是會插入新值
創(chuàng)建實體
@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中不要寫表名,要寫實體名,他會自動轉(zhuǎn)化為表名的。
通過解析方法名創(chuàng)建查詢
上面 findByTitle(String title) 與 findByTitleAndContent(String title, String content) ,沒有寫sql,但框架會自動按名字對上面的方對創(chuàng)建sql。
單元測試
@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ù)庫,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- SpringData JPA基本/高級/多數(shù)據(jù)源的使用詳解
- SpringBoot+Spring?Data?JPA整合H2數(shù)據(jù)庫的示例代碼
- 解決Spring Data Jpa 實體類自動創(chuàng)建數(shù)據(jù)庫表失敗問題
- Springboot使用Spring Data JPA實現(xiàn)數(shù)據(jù)庫操作
- Spring Data JPA進行數(shù)據(jù)分頁與排序的方法
- springboot使用spring-data-jpa操作MySQL數(shù)據(jù)庫
- 詳解基于Spring Boot與Spring Data JPA的多數(shù)據(jù)源配置
- Spring?Data?JPA框架的核心概念與Repository接口詳解
相關(guān)文章
Java實現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例
今天小編就為大家分享一篇關(guān)于Java實現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
使用maven-archetype-plugin現(xiàn)有項目生成腳手架的方法
這篇文章主要介紹了使用maven-archetype-plugin現(xiàn)有項目生成腳手架的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
詳解Java如何實現(xiàn)百萬數(shù)據(jù)excel導(dǎo)出功能
這篇文章主要為大家詳細介紹了Java如何實現(xiàn)百萬數(shù)據(jù)excel導(dǎo)出功能,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下2023-02-02
hotspot解析jdk1.8?Unsafe類park和unpark方法使用
這篇文章主要為大家介紹了hotspot解析jdk1.8?Unsafe類park和unpark方法使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01
SpringBoot和Vue2項目配置https協(xié)議過程
本文詳細介紹了SpringBoot項目和Vue2項目的部署流程及SSL證書配置,對于SpringBoot項目,需將.pfx文件放入resources目錄并配置server,然后打包部署,Vue2項目中,涉及檢查nginx的SSL模塊、編譯新的nginx文件2024-10-10
Java源碼解析之Gateway請求轉(zhuǎn)發(fā)
今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著Gateway請求轉(zhuǎn)發(fā)展開,文中有非常詳細介紹及代碼示例,需要的朋友可以參考下2021-06-06

