Spring Data JPA例子[基于Spring Boot、Mysql]

閱讀目錄

  • 關于Spring Data
  • 關于Spring Data子項目
  • 關于Spring Data Jpa
  • 例子,Spring Boot + Spring Data Jpa
  • 運行、測試程序
  • 程序源碼
  • 參考資料

關于Spring Data

Spring社區的一個頂級工程,主要用于簡化數據(關系型&非關系型)訪問,如果我們使用Spring Data來開發程序的話,那么可以省去很多低級別的數據訪問操作,如編寫數據查詢語句、DAO類等,我們僅需要編寫一些抽象接口并定義相關操作即可,Spring會在運行期間的時候創建代理實例來實現我們接口中定義的操作。

關于Spring Data子項目

Spring Data擁有很多子項目,除了Spring Data Jpa外,還有如下子項目。

Spring Data Commons

Spring Data MongoDB

Spring Data Redis

Spring Data Solr

Spring Data Gemfire

Spring Data REST

Spring Data Neo4j

關于Spring Data Jpa

Spring Data Jpa是Spring Data的一個子項目,主要用于簡化數據訪問層的實現,使用Spring Data Jpa可以輕松實現增刪改查、分頁、排序等。

例子,Spring Boot + Spring Data Jpa

1、添加POM.XML文件

如下所示:

復制代碼
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-data-jpa-example</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.4.4.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.7</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
復制代碼

其中,spring-boot-starter-parent會加載Spring Boot應用所需的所有默認配置;

spring-boot-starter-data-jpa會下載所有Spring Data Jpa所需的依賴;

添加spring-boot-starter-web是因為我們的工程是一個Web應用;

另外我們的數據庫是mysql,所以還需要mysql-connector-java依賴;

由于使用了緩存,所以再添加一個spring-boot-starter-cache依賴;

2、編寫實體類User

復制代碼
package com.example.domain;import java.io.Serializable;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;@Entity
@NamedQuery(name = "User.findByName", query = "select name,address from User u where u.name=?1")
public class User implements Serializable
{private static final long serialVersionUID = 1L;@Idlong id;@Column(name = "name")String name;@Column(name = "address")String address;public long getId(){return id;}public void setId(long id){this.id = id;}public String getName(){return name;}public void setName(String name){this.name = name;}public String getAddress(){return address;}public void setAddress(String address){this.address = address;}}
復制代碼

其它沒啥好說的,注意下這里的@NamedQuery注解,大致意思就是讓我們在Repository接口中定義的findByName方法不使用默認的查詢實現,取而代之的是使用這條自定義的查詢語句去查詢,如果這里沒有標注的話,會使用默認實現的。

3、編寫Repository接口

這里將編寫兩個Repository接口,僅僅用于示例,實際中可以合并成一個:

UserJpaRepository 
復制代碼
package com.example.repository;import org.springframework.data.jpa.repository.JpaRepository;import com.example.domain.User;public interface UserJpaRepository extends JpaRepository<User,Long> {}
復制代碼

這里的UserJpaRepository接口實現了JpaRepository接口;

實際上JpaRepository實現了PagingAndSortingRepository接口,PagingAndSortingRepository接口實現了CrudRepository接口,CrudRepository接口實現了Repository接口;

簡單說明下:

Repository接口是一個標識接口,里面是空的;

CrudRepository接口定義了增刪改查方法;

PagingAndSortingRepository接口用于分頁和排序;

由于JpaRepository接口繼承了以上所有接口,所以擁有它們聲明的所有方法;

另外注意下,以findAll方法為例,JpaRepository接口返回的是List, PagingAndSortingRepository和CrudRepository返回的是迭代器;

UserRepository 
復制代碼
package com.example.repository;import java.util.List;import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;import com.example.domain.User;public interface UserRepository extends Repository<User, Long>
{List<User> findByNameAndAddress(String name, String address);@Query(value = "from User u where u.name=:name")List<User> findByName1(@Param("name") String name);@Query(value = "select * from #{#entityName} u where u.name=?1", nativeQuery = true)List<User> findByName2(String name);List<User> findByName(String name);
}
復制代碼

這里的UserRepository接口主要定義了一些查詢方法;

比如這里的findByNameAndAddress和findByName方法,我們是不需要額外定義其它查詢語句就可以直接執行的,Spring Data Jpa會根據實體類的屬性名字以及方法名自動實現該方法;PS:由于我們在實體類中聲明了@NamedQuery注解,實際上findByName方法會使用@NamedQuery注解標注的查詢語句去查詢;

另外這里的findByName1方法使用了HQL語句查詢;

findByName2方法使用了原始的sql語句查詢;

4、編寫Service

service接口:

復制代碼
package com.example.service;import java.util.List;import com.example.domain.User;public interface IUserService
{public List<User> findAll();public void saveUser(User book);public User findOne(long id);public void delete(long id);public List<User> findByName(String name);}
復制代碼

接口實現類:

復制代碼
package com.example.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import com.example.domain.User;
import com.example.repository.UserRepository;
import com.example.repository.UserJpaRepository;
import com.example.service.IUserService;@Service
@Transactional
public class UserServiceImpl implements IUserService
{@Autowiredprivate UserJpaRepository userJpaRepository;@Autowiredprivate UserRepository userRepository;public List<User> findAll(){return userJpaRepository.findAll();}public List<User> findByName(String name){List<User> userList1 = userRepository.findByName1(name);List<User> userList2 = userRepository.findByName2(name);List<User> userList3 = userRepository.findByNameAndAddress(name, "3");System.out.println("userList1:" + userList1);System.out.println("userList2:" + userList2);System.out.println("userList3:" + userList3);return userRepository.findByName(name);}public void saveUser(User book){userJpaRepository.save(book);}@Cacheable("users")public User findOne(long id){System.out.println("Cached Pages");return userJpaRepository.findOne(id);}public void delete(long id){userJpaRepository.delete(id);}
}
復制代碼

這個沒啥好說的,調用Repository接口接口的方法即可。

5、編寫Controller

Controller也沒啥好說的,調用Service即可,注意下這里的Controller使用@RestController注解來標注,另外URL路徑命名按照RESTful風格來命名;

復制代碼
package com.example.web;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.example.domain.User;
import com.example.service.IUserService;@RestController
@RequestMapping(value = "/users")
public class UserController
{@Autowiredprivate IUserService userService;@RequestMapping(value = "/add/{id}/{name}/{address}")public User addUser(@PathVariable int id, @PathVariable String name,@PathVariable String address){User user = new User();user.setId(id);user.setName(name);user.setAddress(address);userService.saveUser(user);return user;}@RequestMapping(value = "/delete/{id}")public void deleteBook(@PathVariable int id){userService.delete(id);}@RequestMapping(value = "/")public List<User> getBooks(){return userService.findAll();}@RequestMapping(value = "/{id}")public User getUser(@PathVariable int id){User user = userService.findOne(id);return user;}@RequestMapping(value = "/search/name/{name}")public List<User> getBookByName(@PathVariable String name){List<User> users = userService.findByName(name);return users;}}
復制代碼

6、配置datasource

在application.properties文件中添加如下配置:

復制代碼
spring.jpa.show-sql = true
logging.level.org.springframework.data=DEBUG
spring.jpa.hibernate.ddl-auto=spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
復制代碼

如果你使用STS IDE的話,這些屬性配置都會自動提示的,省的去查找。

想查看spring.datasource的配置,可以參考這個類:DataSourceProperties.java

7、編寫啟動類

比較簡單,注意下該類所屬的包級別要大于或等于其它類,以保證其它類的注解可以被掃描到。

復制代碼
package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching
public class SpringDataJpaExampleApplication {public static void main(String[] args) {SpringApplication.run(SpringDataJpaExampleApplication.class, args);}
}
復制代碼


本文轉自風一樣的碼農博客園博客,原文鏈接:http://www.cnblogs.com/chenpi/p/6357527.html,如需轉載請自行聯系原作者

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279375.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279375.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279375.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

The way of Webpack learning (IV.) -- Packaging CSS(打包css)

一&#xff1a;目錄結構 二&#xff1a;webpack.config.js的配置 const path require(path);module.exports {mode:development,entry:{app:./src/app.js},output:{path:path.resolve(__dirname,dist),publicPath:./dist/,//設置引入路徑在相對路徑filename:[name].bundle.js…

文本文檔TXT每行開頭結尾加內容批處理代碼

文本文檔TXT每行開頭結尾加內容批處理代碼 讀A.TXT ,每行開頭加&#xff1a;HTMLBodytxt HTMLBodytxt chr(10) aaaaaaaa結尾加&#xff1a;bbbbbbbb處理后的文檔寫入到B.TXT For /f "delims" %%i in (a.txt) do echo HTMLBodytxt HTMLBodytxt chr(10) aaaaaaaa%%…

windows運行對話框_如何在Windows運行對話框中添加文本快捷方式?

windows運行對話框Windows comes prepackaged with a ton of handy run-dialog shortcuts to help you launch apps and tools right from the run box; is it possible to add in your own custom shortcuts? Windows預包裝了許多方便的運行對話框快捷方式&#xff0c;可幫助…

前后臺分離--概念相關

js 包管理器:  1、npm  2、bower 包管理器的作用&#xff1a;&#xff08;之前滿世界找代碼&#xff0c;現在統一地址了。類似于360軟件管家&#xff0c;maven倉庫。&#xff09;  1、復用別人已經寫好的代碼。  2、管理包之間的依賴關系。 JS &#xff1a;語言&#…

Zabbix 3.0 安裝

Zabbix 3.0 For CentOS6安裝 1 概述2 安裝MySQL3 安裝WEB4 安裝Zabbix-Server5配置WEB1概述 對于3.0&#xff0c;官方只提供CentOS7的RPM包&#xff0c;Ubuntu的DEB包&#xff0c;對于CentOS6&#xff0c;默認不提供RPM包&#xff0c;為了照顧到使用CentOS6的兄弟們&#xff0c…

[Hadoop in China 2011] 中興:NoSQL應用現狀及電信業務實踐

http://tech.it168.com/a2011/1203/1283/000001283154.shtml 在今天下午進行的NoSQL系統及應用分論壇中&#xff0c;中興云計算平臺研發總工、中興通訊技術專家委員會專家高洪發表主題演講“NoSQL技術的電信業務實踐”&#xff0c;介紹了NoSQL的發展現狀及其在電信業務中的應用…

qmediaplayer獲取流類型_Java 流API

流相關的接口和類在java.util.stream包中。AutoCloseable接口來自java.lang包。所有流接口從繼承自AutoCloseable接口的BaseStream接口繼承。AutoCloseable|--BaseStream|--IntStream|--LongStream|--DoubleStream|--Stream如果流使用集合作為其數據源&#xff0c;并且集合不需…

田剛:龐加萊猜想與幾何

&#xff08;作者 田剛&#xff09; 時間&#xff1a;2015年11月1日 地點&#xff1a;北京大學北京國際數學研究中心 主題&#xff1a;未來論壇“理解未來”講座北大專場&#xff1a;龐加萊猜想與幾何 田剛&#xff1a; 非常高興能夠有這個機會來參加未來論壇講演。我今天要講的…

進化:從孤膽極客到高效團隊_極客學校:學習Windows 7 –遠程管理

進化:從孤膽極客到高效團隊In this installation of Geek School, we look at how we can administer our machines remotely using Remote Assistance, Remote Desktop, Windows Remote Management also known as WinRM, and PowerShell. 在此Geek School安裝中&#xff0c;我…

新秀翻譯(兩)——使用Java通用配置模板方法模式

假設你發現你已經非常重碼&#xff0c;你可能會考慮使用模板的方法來消除easy重復錯誤代碼。下面是一個示例:以下兩類,他完成了幾乎相同的功能&#xff1a; 實例化并初始化一個Reader來讀取CSV文件。讀取每一行并解析&#xff1b;把每一行的字符填充到Product或Customer對象&am…

框架基礎:深入理解Java注解類型(@Annotation)

注解的概念 注解的官方定義 首先看看官方對注解的描述&#xff1a; An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the opera…

打印墨水調鋼筆墨水_如何節省墨水并改善網站打印質量

打印墨水調鋼筆墨水Printing out web pages you want a hard copy of can be a little hit and miss. Unlike other documents, it is not easy to tell exactly how many pieces of paper will be needed, and whether or not there will be any awkward clipping. Add to thi…

highcharts 怎么去掉鼠標懸停效果_練瑜伽減肥沒效果什么原因?

沒有心的參與&#xff0c;瑜伽就不是瑜伽曾經有很多人問&#xff1a;自己想用瑜伽來減肥&#xff0c;但練習瑜伽這么久&#xff0c;為什么還是減不下來&#xff1f;一點效果都沒有。瑜伽是什么&#xff1f;瑜伽只是一種單純的運動嗎&#xff1f;只讓身體參與進去就可以了嗎&…

百度地圖1

百度地圖BMap的類 BMap的屬性是一些構造函數,主大類有&#xff1a;核心類、基礎類、控件類、覆蓋物類、右鍵菜單類、地圖類型類、地圖吐槽類、服務類、全局類 核心類Map Map&#xff1a;最主要的一個類&#xff0c;集成了其他模塊的方法&#xff0c;是一個集成了整個地圖功能的…

Java基礎學習總結(23)——GUI編程

2019獨角獸企業重金招聘Python工程師標準>>> 一、AWT介紹 所有的可以顯示出來的圖形元素都稱為Component&#xff0c;Component代表了所有的可見的圖形元素&#xff0c;Component里面有一種比較特殊的圖形元素叫Container&#xff0c;Container(容器)在圖形界面里面…

spring-使用配置文件完成JdbcTemplate操作數據庫

一、創建spring項目項目名稱&#xff1a;spring101302二、在項目上添加jar包1.在項目中創建lib目錄/lib2.在lib目錄下添加spring支持commons-logging.jarjunit-4.10.jarlog4j.jarmysql-connector-java-5.1.18-bin.jarspring-beans-3.2.0.RELEASE.jarspring-context-3.2.0.RELEA…

瓦片經緯度及行列號轉換_Slippy map tilenames(瓦片和經緯度換算)

Slippy map tilenames(瓦片和經緯度換算)This article describes the file naming conventions for theSlippy Map application.Tiles are 256 256 pixel PNG filesEachzoom level is a directory, each column is a subdirectory, andeach tile in that column is a fileFilen…

在Windows 7或Vista(或Windows 8.x,Sorta)上禁用Aero

The Windows Aero Glass interface for Windows 7 or Vista requires a decent video card, you won’t be able to use it on an old clunker computer. For those worried about performance, sometimes squeezing every last drop requires disabling Aero. Windows 7或Vist…

一個簡單的JDBC通用工具

支持多種數據庫&#xff0c;統一方式產生連接&#xff0c;最優化、最簡單方式釋放資源。歡迎拍磚&#xff01;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.List; import java.util.Properties…

sfm點云代碼_VisualSFM使用方法與心得

關于VisualSfM的更多內容組合多個模型(What if VisualSFM produces multiple models?)&#xff1a;按照上述步驟進行稀疏重建后&#xff0c;理論上可以得到很好的模型。如果結果產生了多個模型&#xff0c;要想把多個模型合成成一個&#xff0c;點擊菜單中的“SfM->More Fu…