什么是JPA
JPA(Java Persistence API)是Sun官方提出的Java持久化規范。它為Java開發人員提供了一種對象/關聯映射工具來管理Java應用中的關系數據。他的出現主要是為了簡化現有的持久化開發工作和整合ORM技術
Spring Data JPA 是 Spring 基于 ORM 框架、JPA 規范的基礎上封裝的一套JPA應用框架,可使開發者用極簡的代碼即可實現對數據的訪問和操作。它提供了包括增刪改查等在內的常用功能,且易于擴展!學習并使用 Spring Data JPA 可以極大提高開發效率!
Spring Boot中使用JdbcTemplate訪問數據庫
數據源配置
首先,為了連接數據庫需要引入jdbc支持,在pom.xml中引入如下配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
嵌入式數據庫支持
嵌入式數據庫通常用于開發和測試環境。Spring-Boot提供自動配置的嵌入式數據庫有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。
如h3的依賴
<dependency> <groupId>com.h3database</groupId> <artifactId>h3</artifactId> <scope>runtime</scope> </dependency>
mysql數據庫支持
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
編輯配置信息
在 src/main/resources/application.properties 中配置數據源信息
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操作數據庫
Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。
通過JdbcTemplate實現DemoService中定義的數據訪問操作
@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");
}
}
創建對UserService的單元測試用例,通過創建、刪除和查詢來驗證數據庫操作的正確性。
測試用例要增加依賴
<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");
// 查數據庫,應該有5個
Assert.assertEquals(3, demoSerivce.getAllDemo().intValue());
}
}
Spring Boot中使用Spring-data-jpa
為了解決這些大量枯燥的數據操作語句,我們第一個想到的是使用ORM框架,比如:Hibernate。通過整合Hibernate之后,我們以操作Java實體的方式最終將數據改變映射到數據庫表中。
為了解決抽象各個Java實體基本的“增刪改查”操作,我們通常會以泛型的方式封裝一個模板Dao來進行抽象簡化,但是這樣依然不是很方便,我們需要針對每個實體編寫一個繼承自泛型模板Dao的接口,再編寫該接口的實現。雖然一些基礎的數據訪問已經可以得到很好的復用,但是在代碼結構上針對每個實體都會有一堆Dao的接口和實現。
由于模板Dao的實現,使得這些具體實體的Dao層已經變的非?!氨 ?,有一些具體實體的Dao實現可能完全就是對模板Dao的簡單代理,并且往往這樣的實現類可能會出現在很多實體上。Spring-data-jpa的出現正可以讓這樣一個已經很“薄”的數據訪問層變成只是一層接口的編寫方式。
使用方法
添加依賴
<dependency <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
編輯配置信息
在 src/main/resources/application.properties 中配置數據源信息
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的配置屬性,其主要作用是:自動創建、更新、驗證數據庫表結構。該參數的幾種配置如下
創建實體
@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 略
}
創建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中不要寫表名,要寫實體名,他會自動轉化為表名的。
通過解析方法名創建查詢
上面 findByTitle(String title) 與 findByTitleAndContent(String title, String content) ,沒有寫sql,但框架會自動按名字對上面的方對創建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());
}
}
總結
以上所述是小編給大家介紹的Spring boot中使用Spring-data-jpa方便快捷的訪問數據庫,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。