javascript
Springboot使用JPA框架对数据库实现增删改查(附详细代码)
前言
1、本文將詳細闡述如何使用JPA框架對數據庫實現增刪改查操作,業務中比較常見的應用場景幾乎在這里都能看到,并且有詳盡的代碼可供直觀演示,其中遇到的坑也進行了實時標注。
2、JPA的環境配置在前面的章節已有總結,不再贅述,直接上干貨。
環境準備
步驟1:創建實體類對象
步驟2:創建與實體類MerchantInfo相關的JPA接口,并使其繼承JpaRepository接口,泛型傳遞<MerchantInfo, Long>
//此注解必加,表明它是一個bean類,項目啟動后spring容器掃描到該注解,會將該類初始化成bean對象,便于其他程序調用 @Component public interface MerchantInfoJpaRepository extends JpaRepository<MerchantInfo,Long> { }步驟3:SpringBoot主程序入口,如果只用JPA框架,相關的配置只需加@EnableJpaRepositories注解即可
@SpringBootApplication @EnableJpaRepositories public class WebapitestApplication {public static void main(String[] args) {SpringApplication.run(WebapitestApplication.class, args);} }步驟4:創建Controller類
下面是controller類整體格式,后面對數據庫表merchant_info進行增刪改查的所有代碼都會在這個controller類里書寫。
JPA查詢功能
1、findAll()方法:無條件查詢merchant_info表中所有數據
步驟1:Controller中代碼如下:
public class MerchantInfoController {@Autowiredprivate MerchantInfoJpaRepository merchantInfoJpaRepository;/*** JPA findAll() 無條件查詢表中所有數據* @return*/@GetMapping("/getAllMerchantInfo")@ApiOperation(value = "獲取所有商戶信息")public List<MerchantInfo> getAllMerchantInfo(){List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAll();log.info("打印所有商戶列表:{}",merchantInfoList);return merchantInfoList;}}}步驟2:接口調用:http://localhost:8080/getAllMerchantInfo
步驟3:接口返回結果:
2、findById(Long id)方法:根據id查詢merchant_info表中對應的數據
步驟1:Controller中代碼如下:
/*** JPA findById(Long id) 根據主鍵id查詢表中相應數據* @param id* @return*/@GetMapping("/getMerchantById")@ApiOperation(value = "獲取指定id的商戶信息")@ApiImplicitParam(name = "id",value = "商戶id",required = true,defaultValue = "15")public MerchantInfo getMerchantById(@RequestParam(name = "id") Long id){Optional<MerchantInfo> merchantInfoOptional = merchantInfoJpaRepository.findById(id);MerchantInfo merchantInfo = merchantInfoOptional.get();log.info("打印id={}的商戶信息為:{}",id,merchantInfo);return merchantInfo;}步驟2:調用接口:http://localhost:8080/getMerchantById?id=15
步驟3:接口返回結果如下:
3、findAllById(Iterable<ID> var1)方法:根據傳入的多個id集合查詢merchant_info表中對應的數據
步驟1:Controller中代碼
/*** JPA findAllById(Iterable<ID> var1) 查詢多個id表中相應數據* @param ids* @return*/@GetMapping("/getMerchantByIds")@ApiOperation(value = "獲取多個id對應的商戶信息")public List<MerchantInfo> getMerchantByIds(@RequestParam(name = "ids") String ids ){log.info("打印后端接收post請求體數據 String[] ids:{}",ids);//將傳入的數組字符串解析成JsonArray對象JSONArray jsonArray = JSON.parseArray(ids);log.info("打印轉換后的JsonArray對象:{}",jsonArray); List<Long> longList = new ArrayList<Long>();//遍歷jsonArray對象取出id元素并添加到List集合中for (int i = 0; i < jsonArray.size(); i++){longList.add(jsonArray.getLong(i));}log.info("打印轉換后的Long集合:{}",longList);//查詢longList集合中所有id對應的數據List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAllById(longList);log.info("打印商戶集合:{}",merchantInfoList);return merchantInfoList;}步驟2:接口調用:http://localhost:8080/getMerchantByIds?ids=%5B2%2C3%2C6%5D
Note:%5B %2C %5D分別代表[ , ],它們都是URL編碼,實際上ids參數傳遞的是[2, 3, 6]只是不能明文傳輸,必須轉成符合URL編碼規則的格式。
步驟3:接口返回結果如下:
[{"id": 2,"merchantName": "廣州市青豪企業管理有限責任公司","cityName": "溫州","parentId": null,"status": 2,"invitationCode": "126155","createTime": "2021-03-23T03:43:43.000+00:00","updateTime": "2021-04-27T06:47:00.000+00:00","remark": null,"principal": null,"principalPhone": null},{"id": 3,"merchantName": "蘇州合和眾科技有限公司","cityName": "蘇州","parentId": null,"status": 2,"invitationCode": "807624","createTime": "2021-03-24T09:23:05.000+00:00","updateTime": "2021-04-27T06:46:58.000+00:00","remark": null,"principal": null,"principalPhone": null},{"id": 6,"merchantName": "義烏市鈴芝電動車行","cityName": "杭州","parentId": null,"status": 2,"invitationCode": "798048","createTime": "2021-03-23T03:43:43.000+00:00","updateTime": "2021-04-27T06:46:57.000+00:00","remark": null,"principal": null,"principalPhone": null} ]4、findAll(Example<S> example)方法:構建example查詢條件進行查詢
步驟1:Controller中代碼
/*** JPA List<S> findAll(Example<S> example) 構建example查詢條件進行查詢* @param merchantInfo* @return*/@PostMapping("/getMerchantByExample")@ApiOperation(value = "根據example查詢符合條件的商戶信息")public List<MerchantInfo> getMerchantByExample(@RequestBody MerchantInfo merchantInfo){log.info("打印傳入的請求體merchantInfo:{}",merchantInfo);//構建查詢exampleExample<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);//返回數據庫中所有符合example查詢條件對應的數據List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAll(merchantInfoExample);log.info("打印符合條件的商戶列表:{}",merchantInfoList);return merchantInfoList;}步驟2:接口調用
post:
http://localhost:8080/getMerchantByExample
parameters:
步驟3:接口返回結果
[{"id": 1,"merchantName": "廣州澤天君成科技有限公司","cityName": "廣州","parentId": null,"status": 2,"invitationCode": "207717","createTime": "2021-03-23T03:37:00.000+00:00","updateTime": "2021-04-27T09:02:11.000+00:00","remark": null,"principal": null,"principalPhone": null},{"id": 4,"merchantName": "成都歐韻聚網絡科技有限公司","cityName": "廣州","parentId": null,"status": 2,"invitationCode": "859655","createTime": "2021-03-23T03:37:00.000+00:00","updateTime": "2021-05-10T03:22:48.000+00:00","remark": null,"principal": null,"principalPhone": null} ]5、findAll(Example<S> example, Pageable pageable)方法:構建example查詢條件并進行分頁查詢
步驟1:Controller中代碼
/*** JPA <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) 構建example查詢條件,并進行分頁查詢* note: page起始頁 0* @param page* @param size* @param merchantInfo* @return*/@PostMapping("/findAllByPageAble/{page}/{size}")@ApiOperation(value = "查詢結果翻頁處理")public List<MerchantInfo> findAllByPageAble(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody MerchantInfo merchantInfo){//根據前端傳入的page和size,構建Pageable對象,用于后續的分頁查詢Pageable pageable = PageRequest.of(page-1,size);//根據前端傳入的請求體構建Example查詢條件Example<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);Page<MerchantInfo> merchantInfoPage = merchantInfoJpaRepository.findAll(merchantInfoExample, pageable);//獲取對應頁的數據內容List<MerchantInfo> merchantInfoList = merchantInfoPage.getContent();log.info("打印第{}頁,每頁數量{}條,\n該頁查詢結果為:{}",page,size,merchantInfoList);return merchantInfoList;}步驟2:接口調用
post:http://localhost:8080/findAllByPageAble/2/3
parameters:
步驟3:接口返回結果
[{"id": 12,"merchantName": "中山市古鎮超途餐飲服務部","cityName": "廣州","parentId": null,"status": 2,"invitationCode": "689589","createTime": "2021-03-23T03:43:43.000+00:00","updateTime": "2021-05-10T03:22:34.000+00:00","remark": null,"principal": null,"principalPhone": null},{"id": 13,"merchantName": "廣州騎士之家數字科技有限公司","cityName": "廣州","parentId": null,"status": 2,"invitationCode": "513000","createTime": "2021-03-23T03:43:43.000+00:00","updateTime": "2021-04-27T06:46:52.000+00:00","remark": null,"principal": null,"principalPhone": null},{"id": 16,"merchantName": "六安市煜祥人力資源開發有限公司(深圳)","cityName": "廣州","parentId": null,"status": 2,"invitationCode": "422057","createTime": "2021-03-23T03:43:43.000+00:00","updateTime": "2021-05-10T03:22:35.000+00:00","remark": null,"principal": null,"principalPhone": null} ]JPA新增、修改功能
1、save(S s)方法:可對傳入的單個Entity對象映射到數據庫表中實現新增數據或修改表數據功能
步驟1:Controller中代碼
/*** JPA <S extends T> S save(S s) save方法可是實現新增或修改功能* @apiNote 傳入一個Entity對象,若該對象中存在主鍵id,則是修改;若主鍵不存在,則是新增* @param merchantInfo* @return*/@PostMapping("/saveMerchantByEntity")@ApiOperation(value = "新增或修改商戶信息")public MerchantInfo saveMerchantByEntity(@RequestBody MerchantInfo merchantInfo){//判斷主鍵是否存在,若存在,則修改該主鍵對應的表記錄if(merchantInfo.getId()!= null && merchantInfo.getId() > 0){MerchantInfo merchantInfo1 = merchantInfoJpaRepository.findById(merchantInfo.getId()).get();/*** copyProperties(source,target,ignoreProperties) 將源對象屬性值反射到目標對象對應的屬性上,如果不加ignoreProperties參數* 則源對象中屬性值為null的值會覆蓋掉目標對象中對應屬性不為null的值,ignoreProperties參數可以指定源對象中不覆蓋目標對象的屬性。* 如果源對象不存在某個屬性,而目標對象存在某個屬性,這種情況反射后,目標對象的該屬性不會被覆蓋*/BeanUtils.copyProperties(merchantInfo,merchantInfo1,new String[]{"createTime","invitationCode"});merchantInfo1.setUpdateTime(new Date());return merchantInfoJpaRepository.save(merchantInfo1);}else{//若主鍵id不存在,則新增一條記錄到數據庫表中merchantInfo.setCreateTime(new Date());merchantInfo.setUpdateTime(new Date());MerchantInfo merchantInfo1 = merchantInfoJpaRepository.save(merchantInfo);return merchantInfo1;}}步驟2:接口調用
post:http://localhost:8080/saveMerchantByEntity
parameters 1:
parameters 2:
//請求體中存在id主鍵54,因此是修改 {"id":54,"cityName": "大理01","invitationCode": "333333","merchantName": "大理測試商戶099","principal": "馬二麻子","principalPhone": "18900000000" }步驟3:接口返回結果
response 1:
response 2:
{"id": 54,"merchantName": "大理測試商戶099","cityName": "大理01","parentId": null,"status": null,"invitationCode": "333333","createTime": "2021-05-12T08:56:26.000+00:00","updateTime": "2021-05-12T09:01:40.810+00:00","remark": null,"principal": "馬二麻子","principalPhone": "18900000000" }Note:
a)接口傳parameters 1,無id,則新增一條表記錄,自增生成的主鍵ID值54,見response 1;
b)接口傳parameters 2,有id,則修改該id對應的表記錄,見response 1。
2、saveAll(Iterable<S> iterable)方法:可對傳入的多個Entity對象集合映射到數據庫表中實現批量新增數據或修改表數據功能
步驟1:Controller中代碼
/*** JPA <S extends T> List<S> saveAll(Iterable<S> iterable) saveAll方法可實現批量新增或修改功能* @param merchantInfoList* @return*/@PostMapping("/saveMerchantByEntityList")@ApiOperation(value = "批量新增或修改商戶信息")public List<MerchantInfo> saveMerchantByEntityList(@RequestBody List<MerchantInfo> merchantInfoList){//創建一個新List集合,裝載處理后的Entity對象List<MerchantInfo> updateMerchantList = new ArrayList<MerchantInfo>();for (MerchantInfo merchantInfo : merchantInfoList){if (merchantInfo.getId() != null && merchantInfo.getId() > 0){//獲取數據庫中對應id的原始數據映射到entityMerchantInfo merchantInfo1 = merchantInfoJpaRepository.findById(merchantInfo.getId()).get();BeanUtils.copyProperties(merchantInfo,merchantInfo1,new String[]{"createTime","invitationCode"});merchantInfo1.setUpdateTime(new Date());updateMerchantList.add(merchantInfo1);}else{merchantInfo.setCreateTime(new Date());merchantInfo.setUpdateTime(new Date());updateMerchantList.add(merchantInfo);}}log.info("打印處理后的MerchantInfo對象集合:\n{}",updateMerchantList);//批量進行新增或修改List<MerchantInfo> merchantInfoList1 = merchantInfoJpaRepository.saveAll(updateMerchantList);return merchantInfoList1;}步驟2:接口調用
post:http://localhost:8090/saveMerchantByEntityList
parameters:
步驟3:接口返回結果
//前三條數據進行了修改,最后一條數據新增插入數據庫中。 [{"id": 50,"merchantName": "大理測試商戶01","cityName": "大理01","parentId": null,"status": 1,"invitationCode": "111222","createTime": "2021-05-12T03:29:23.000+00:00","updateTime": "2021-05-12T03:43:45.732+00:00","remark": null,"principal": "臧三","principalPhone": "13811112222"},{"id": 51,"merchantName": "大理測試商戶02","cityName": "大理01","parentId": null,"status": 1,"invitationCode": "2222333","createTime": "2021-05-12T03:29:23.000+00:00","updateTime": "2021-05-12T03:43:45.845+00:00","remark": null,"principal": "女四","principalPhone": "1381111333333"},{"id": 52,"merchantName": "大理測試商戶03","cityName": "大理01","parentId": null,"status": 1,"invitationCode": "333444","createTime": "2021-05-12T03:29:23.000+00:00","updateTime": "2021-05-12T03:43:45.923+00:00","remark": null,"principal": "萬五","principalPhone": "13811114444"},{"id": 53,"merchantName": "大理測試商戶04","cityName": "大理01","parentId": null,"status": 1,"invitationCode": "713713","createTime": "2021-05-12T03:43:45.923+00:00","updateTime": "2021-05-12T03:43:45.923+00:00","remark": null,"principal": "萬五趙六","principalPhone": "13811115555"} ]JPA刪除功能
1、deleteAll()方法:刪除merchant_info表中所有數據
2、deleteById(Long)方法:刪除merchant_info表中對應id的數據
/*** JPA deleteById(Long) 刪除對應id的表數據* 刪除數據庫表中對應id的條目* @param id*/@GetMapping("/deleteMerchantInfoById")@ApiOperation(value = "刪除merchant_info表中對應id的數據")public void deleteMerchantInfoById(@RequestParam("id") Long id){merchantInfoJpaRepository.deleteById(id);}3、delete(T t)方法:刪除Entity對應的表數據
/*** JPA delete(T t) 刪除Entity對應的表數據* @param merchantInfo*/@PostMapping("/deleteMerchantInfoByEntity")@ApiOperation(value = "刪除Entity對象映射對應的表數據")public void deleteMerchantInfoByEntity(@RequestBody MerchantInfo merchantInfo){log.info("打印請求體merchantInfo對象:{}",merchantInfo);Example<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);MerchantInfo merchantInfo1 = merchantInfoJpaRepository.findOne(merchantInfoExample).get();merchantInfoJpaRepository.delete(merchantInfo1);}4、deleteAll(Iterable<? extends T> iterable)方法:刪除merchant_info表中多條記錄
/*** JPA deleteAll(Iterable<? extends T> iterable)* @param merchantInfo*/@PostMapping("/deleteMerchantInfoByEntitysList")@ApiOperation(value = "刪除merchant_info表中多條記錄")public void deleteMerchantInfoByEntitysList(@RequestBody MerchantInfo merchantInfo){Example<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAll(merchantInfoExample);merchantInfoJpaRepository.deleteAll(merchantInfoList);}附merchant_info表結構
CREATE TABLE `merchant_info` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主鍵id',`merchant_name` varchar(150) DEFAULT NULL COMMENT '商戶名稱',`city_name` varchar(255) DEFAULT NULL COMMENT '城市名稱',`parent_id` bigint DEFAULT NULL COMMENT '父商戶Id',`status` int DEFAULT '1' COMMENT '狀態:1:有效 2:無效',`invitation_code` varchar(64) DEFAULT NULL COMMENT '邀請碼',`create_time` datetime NOT NULL COMMENT '創建時間',`update_time` datetime NOT NULL COMMENT '修改時間',`remark` varchar(255) DEFAULT NULL COMMENT '備注',`principal` varchar(64) DEFAULT NULL COMMENT '負責人',`principal_phone` varchar(64) DEFAULT NULL COMMENT '負責人電話',PRIMARY KEY (`id`) )總結
以上是生活随笔為你收集整理的Springboot使用JPA框架对数据库实现增删改查(附详细代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux shell 基础语法
- 下一篇: SpringBoot使用mybatis