javascript
Springboot使用JPA框架对数据库实现增删改查(附详细代码)
前言
1、本文將詳細(xì)闡述如何使用JPA框架對數(shù)據(jù)庫實(shí)現(xiàn)增刪改查操作,業(yè)務(wù)中比較常見的應(yīng)用場景幾乎在這里都能看到,并且有詳盡的代碼可供直觀演示,其中遇到的坑也進(jìn)行了實(shí)時(shí)標(biāo)注。
2、JPA的環(huán)境配置在前面的章節(jié)已有總結(jié),不再贅述,直接上干貨。
環(huán)境準(zhǔn)備
步驟1:創(chuàng)建實(shí)體類對象
步驟2:創(chuàng)建與實(shí)體類MerchantInfo相關(guān)的JPA接口,并使其繼承JpaRepository接口,泛型傳遞<MerchantInfo, Long>
//此注解必加,表明它是一個(gè)bean類,項(xiàng)目啟動(dòng)后spring容器掃描到該注解,會將該類初始化成bean對象,便于其他程序調(diào)用 @Component public interface MerchantInfoJpaRepository extends JpaRepository<MerchantInfo,Long> { }步驟3:SpringBoot主程序入口,如果只用JPA框架,相關(guān)的配置只需加@EnableJpaRepositories注解即可
@SpringBootApplication @EnableJpaRepositories public class WebapitestApplication {public static void main(String[] args) {SpringApplication.run(WebapitestApplication.class, args);} }步驟4:創(chuàng)建Controller類
下面是controller類整體格式,后面對數(shù)據(jù)庫表merchant_info進(jìn)行增刪改查的所有代碼都會在這個(gè)controller類里書寫。
JPA查詢功能
1、findAll()方法:無條件查詢merchant_info表中所有數(shù)據(jù)
步驟1:Controller中代碼如下:
public class MerchantInfoController {@Autowiredprivate MerchantInfoJpaRepository merchantInfoJpaRepository;/*** JPA findAll() 無條件查詢表中所有數(shù)據(jù)* @return*/@GetMapping("/getAllMerchantInfo")@ApiOperation(value = "獲取所有商戶信息")public List<MerchantInfo> getAllMerchantInfo(){List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAll();log.info("打印所有商戶列表:{}",merchantInfoList);return merchantInfoList;}}}步驟2:接口調(diào)用:http://localhost:8080/getAllMerchantInfo
步驟3:接口返回結(jié)果:
2、findById(Long id)方法:根據(jù)id查詢merchant_info表中對應(yīng)的數(shù)據(jù)
步驟1:Controller中代碼如下:
/*** JPA findById(Long id) 根據(jù)主鍵id查詢表中相應(yīng)數(shù)據(jù)* @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:調(diào)用接口:http://localhost:8080/getMerchantById?id=15
步驟3:接口返回結(jié)果如下:
3、findAllById(Iterable<ID> var1)方法:根據(jù)傳入的多個(gè)id集合查詢merchant_info表中對應(yīng)的數(shù)據(jù)
步驟1:Controller中代碼
/*** JPA findAllById(Iterable<ID> var1) 查詢多個(gè)id表中相應(yīng)數(shù)據(jù)* @param ids* @return*/@GetMapping("/getMerchantByIds")@ApiOperation(value = "獲取多個(gè)id對應(yīng)的商戶信息")public List<MerchantInfo> getMerchantByIds(@RequestParam(name = "ids") String ids ){log.info("打印后端接收post請求體數(shù)據(jù) String[] ids:{}",ids);//將傳入的數(shù)組字符串解析成JsonArray對象JSONArray jsonArray = JSON.parseArray(ids);log.info("打印轉(zhuǎn)換后的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("打印轉(zhuǎn)換后的Long集合:{}",longList);//查詢longList集合中所有id對應(yīng)的數(shù)據(jù)List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAllById(longList);log.info("打印商戶集合:{}",merchantInfoList);return merchantInfoList;}步驟2:接口調(diào)用:http://localhost:8080/getMerchantByIds?ids=%5B2%2C3%2C6%5D
Note:%5B %2C %5D分別代表[ , ],它們都是URL編碼,實(shí)際上ids參數(shù)傳遞的是[2, 3, 6]只是不能明文傳輸,必須轉(zhuǎn)成符合URL編碼規(guī)則的格式。
步驟3:接口返回結(jié)果如下:
[{"id": 2,"merchantName": "廣州市青豪企業(yè)管理有限責(zé)任公司","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": "義烏市鈴芝電動(dòng)車行","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)方法:構(gòu)建example查詢條件進(jìn)行查詢
步驟1:Controller中代碼
/*** JPA List<S> findAll(Example<S> example) 構(gòu)建example查詢條件進(jìn)行查詢* @param merchantInfo* @return*/@PostMapping("/getMerchantByExample")@ApiOperation(value = "根據(jù)example查詢符合條件的商戶信息")public List<MerchantInfo> getMerchantByExample(@RequestBody MerchantInfo merchantInfo){log.info("打印傳入的請求體merchantInfo:{}",merchantInfo);//構(gòu)建查詢exampleExample<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);//返回?cái)?shù)據(jù)庫中所有符合example查詢條件對應(yīng)的數(shù)據(jù)List<MerchantInfo> merchantInfoList = merchantInfoJpaRepository.findAll(merchantInfoExample);log.info("打印符合條件的商戶列表:{}",merchantInfoList);return merchantInfoList;}步驟2:接口調(diào)用
post:
http://localhost:8080/getMerchantByExample
parameters:
步驟3:接口返回結(jié)果
[{"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": "成都?xì)W韻聚網(wǎng)絡(luò)科技有限公司","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)方法:構(gòu)建example查詢條件并進(jìn)行分頁查詢
步驟1:Controller中代碼
/*** JPA <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) 構(gòu)建example查詢條件,并進(jìn)行分頁查詢* note: page起始頁 0* @param page* @param size* @param merchantInfo* @return*/@PostMapping("/findAllByPageAble/{page}/{size}")@ApiOperation(value = "查詢結(jié)果翻頁處理")public List<MerchantInfo> findAllByPageAble(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody MerchantInfo merchantInfo){//根據(jù)前端傳入的page和size,構(gòu)建Pageable對象,用于后續(xù)的分頁查詢Pageable pageable = PageRequest.of(page-1,size);//根據(jù)前端傳入的請求體構(gòu)建Example查詢條件Example<MerchantInfo> merchantInfoExample = Example.of(merchantInfo);Page<MerchantInfo> merchantInfoPage = merchantInfoJpaRepository.findAll(merchantInfoExample, pageable);//獲取對應(yīng)頁的數(shù)據(jù)內(nèi)容List<MerchantInfo> merchantInfoList = merchantInfoPage.getContent();log.info("打印第{}頁,每頁數(shù)量{}條,\n該頁查詢結(jié)果為:{}",page,size,merchantInfoList);return merchantInfoList;}步驟2:接口調(diào)用
post:http://localhost:8080/findAllByPageAble/2/3
parameters:
步驟3:接口返回結(jié)果
[{"id": 12,"merchantName": "中山市古鎮(zhèn)超途餐飲服務(wù)部","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": "廣州騎士之家數(shù)字科技有限公司","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": "六安市煜祥人力資源開發(fā)有限公司(深圳)","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)方法:可對傳入的單個(gè)Entity對象映射到數(shù)據(jù)庫表中實(shí)現(xiàn)新增數(shù)據(jù)或修改表數(shù)據(jù)功能
步驟1:Controller中代碼
/*** JPA <S extends T> S save(S s) save方法可是實(shí)現(xiàn)新增或修改功能* @apiNote 傳入一個(gè)Entity對象,若該對象中存在主鍵id,則是修改;若主鍵不存在,則是新增* @param merchantInfo* @return*/@PostMapping("/saveMerchantByEntity")@ApiOperation(value = "新增或修改商戶信息")public MerchantInfo saveMerchantByEntity(@RequestBody MerchantInfo merchantInfo){//判斷主鍵是否存在,若存在,則修改該主鍵對應(yīng)的表記錄if(merchantInfo.getId()!= null && merchantInfo.getId() > 0){MerchantInfo merchantInfo1 = merchantInfoJpaRepository.findById(merchantInfo.getId()).get();/*** copyProperties(source,target,ignoreProperties) 將源對象屬性值反射到目標(biāo)對象對應(yīng)的屬性上,如果不加ignoreProperties參數(shù)* 則源對象中屬性值為null的值會覆蓋掉目標(biāo)對象中對應(yīng)屬性不為null的值,ignoreProperties參數(shù)可以指定源對象中不覆蓋目標(biāo)對象的屬性。* 如果源對象不存在某個(gè)屬性,而目標(biāo)對象存在某個(gè)屬性,這種情況反射后,目標(biāo)對象的該屬性不會被覆蓋*/BeanUtils.copyProperties(merchantInfo,merchantInfo1,new String[]{"createTime","invitationCode"});merchantInfo1.setUpdateTime(new Date());return merchantInfoJpaRepository.save(merchantInfo1);}else{//若主鍵id不存在,則新增一條記錄到數(shù)據(jù)庫表中merchantInfo.setCreateTime(new Date());merchantInfo.setUpdateTime(new Date());MerchantInfo merchantInfo1 = merchantInfoJpaRepository.save(merchantInfo);return merchantInfo1;}}步驟2:接口調(diào)用
post:http://localhost:8080/saveMerchantByEntity
parameters 1:
parameters 2:
//請求體中存在id主鍵54,因此是修改 {"id":54,"cityName": "大理01","invitationCode": "333333","merchantName": "大理測試商戶099","principal": "馬二麻子","principalPhone": "18900000000" }步驟3:接口返回結(jié)果
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對應(yīng)的表記錄,見response 1。
2、saveAll(Iterable<S> iterable)方法:可對傳入的多個(gè)Entity對象集合映射到數(shù)據(jù)庫表中實(shí)現(xiàn)批量新增數(shù)據(jù)或修改表數(shù)據(jù)功能
步驟1:Controller中代碼
/*** JPA <S extends T> List<S> saveAll(Iterable<S> iterable) saveAll方法可實(shí)現(xiàn)批量新增或修改功能* @param merchantInfoList* @return*/@PostMapping("/saveMerchantByEntityList")@ApiOperation(value = "批量新增或修改商戶信息")public List<MerchantInfo> saveMerchantByEntityList(@RequestBody List<MerchantInfo> merchantInfoList){//創(chuàng)建一個(gè)新List集合,裝載處理后的Entity對象List<MerchantInfo> updateMerchantList = new ArrayList<MerchantInfo>();for (MerchantInfo merchantInfo : merchantInfoList){if (merchantInfo.getId() != null && merchantInfo.getId() > 0){//獲取數(shù)據(jù)庫中對應(yīng)id的原始數(shù)據(jù)映射到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);//批量進(jìn)行新增或修改List<MerchantInfo> merchantInfoList1 = merchantInfoJpaRepository.saveAll(updateMerchantList);return merchantInfoList1;}步驟2:接口調(diào)用
post:http://localhost:8090/saveMerchantByEntityList
parameters:
步驟3:接口返回結(jié)果
//前三條數(shù)據(jù)進(jìn)行了修改,最后一條數(shù)據(jù)新增插入數(shù)據(jù)庫中。 [{"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表中所有數(shù)據(jù)
2、deleteById(Long)方法:刪除merchant_info表中對應(yīng)id的數(shù)據(jù)
/*** JPA deleteById(Long) 刪除對應(yīng)id的表數(shù)據(jù)* 刪除數(shù)據(jù)庫表中對應(yīng)id的條目* @param id*/@GetMapping("/deleteMerchantInfoById")@ApiOperation(value = "刪除merchant_info表中對應(yīng)id的數(shù)據(jù)")public void deleteMerchantInfoById(@RequestParam("id") Long id){merchantInfoJpaRepository.deleteById(id);}3、delete(T t)方法:刪除Entity對應(yīng)的表數(shù)據(jù)
/*** JPA delete(T t) 刪除Entity對應(yīng)的表數(shù)據(jù)* @param merchantInfo*/@PostMapping("/deleteMerchantInfoByEntity")@ApiOperation(value = "刪除Entity對象映射對應(yīng)的表數(shù)據(jù)")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表結(jié)構(gòu)
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 '狀態(tài):1:有效 2:無效',`invitation_code` varchar(64) DEFAULT NULL COMMENT '邀請碼',`create_time` datetime NOT NULL COMMENT '創(chuàng)建時(shí)間',`update_time` datetime NOT NULL COMMENT '修改時(shí)間',`remark` varchar(255) DEFAULT NULL COMMENT '備注',`principal` varchar(64) DEFAULT NULL COMMENT '負(fù)責(zé)人',`principal_phone` varchar(64) DEFAULT NULL COMMENT '負(fù)責(zé)人電話',PRIMARY KEY (`id`) )總結(jié)
以上是生活随笔為你收集整理的Springboot使用JPA框架对数据库实现增删改查(附详细代码)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux shell 基础语法
- 下一篇: SpringBoot使用mybatis