淺析JPA分類表的操作函數(shù)
這里說的分類表是指一般系統(tǒng)中用到的分類管理的表。
結(jié)構(gòu)如下:
CREATE TABLE `categories` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `parent_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '父分類ID', `code` varchar(255) NOT NULL DEFAULT '' COMMENT '分類代碼', `title` varchar(255) NOT NULL DEFAULT '' COMMENT '分類名稱', `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '狀態(tài)1啟用0禁用', `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
實(shí)體類,如下 :
@Entity @DynamicUpdate @Table(name = "categories") public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private BigInteger id; // 為了設(shè)置關(guān)聯(lián)關(guān)系,需要注釋掉. // 反正這里沒搞明白,沒設(shè)關(guān)聯(lián)關(guān)系前,設(shè)了Column()返回的數(shù)據(jù)中字段不對(duì)了。 // 這里后面再研究吧 // private BigInteger parent_id; @CreationTimestamp @Column(nullable = false, updatable = false) private Date created_at; @UpdateTimestamp @Column(nullable = false) private Date updated_at; private String title; private String code; private int status; // 中間省略 set get 代碼 // 關(guān)聯(lián)關(guān)系 @ManyToOne // 查不到記錄就忽略 @NotFound(action= NotFoundAction.IGNORE) // 外鍵是parent_id @JoinColumn(name = "parent_id") private Category parent; public Category getParent() { return parent; } public void setParent(Category p) { this.parent = p; } }
Repository :
public interface CategoryRepository extends JpaRepository<Category, BigInteger>, JpaSpecificationExecutor<Category> { List<Category> findAllByCode(String code); @Query(value = "select * from categories WHERE parent_id=?1 ", nativeQuery = true) List<Category> findAllByParentId(BigInteger pid); @Transactional @Modifying @Query(value="update Category c set c.status=?2 where c.id in ?1") void updateStatusById(List<BigInteger> ids, Integer status); }
下面是Controller:
@RestController @RequestMapping(value = "/api/category") public class CategoryController { private CategoryRepository categoryRepository; public CategoryController(CategoryRepository categoryRepository) { this.categoryRepository = categoryRepository; } @GetMapping(value = "fetch-child") public List<Category> getChildren(@RequestParam(value = "id", required = true, defaultValue = "0") BigInteger id) { return categoryRepository.findAllByParentId(id); } /** * 修改記錄 * @param category * @return */ @PostMapping(value = "") public @ResponseBody String store(@RequestBody StoreCategoryData category) { System.out.println(category.toString()); Optional<Category> row = categoryRepository.findById(category.parentId); if (row.isPresent()) { Category p = row.get(); Category c = new Category(); c.setParent(p); c.setTitle(category.title); c.setCode(category.code); categoryRepository.save(c); return "saved"; } throw new RuntimeException("父分類不存在"); } }
StoreCategoryData:
public class StoreCategoryData { public String title; public String code; public BigInteger parentId; }
這個(gè)類是為了新建記錄時(shí)用的。別問為什么,我自己研究出來的,因?yàn)槲也恢肋€有其它什么好辦法。
1,前端需要一個(gè)列表,顯示:父類名稱 +當(dāng)前分類的信息。
由于記錄中只有一個(gè)parent_id來關(guān)聯(lián)父分類,所以用sql的寫法就是寫個(gè)left join就好了。把要查的查出來。這種事交給php那是非常簡單。
Java不行啊,尤其是JPA。
查了查文檔,設(shè)置關(guān)聯(lián)關(guān)系可能是比較優(yōu)雅的方式。
所以,有了實(shí)體類中的@ManyToOne的注釋,因?yàn)榧恿诉@個(gè)屬性,原先的parent_id字段就得隱藏。這里太明白為什么,留待以后研究。
加了關(guān)聯(lián)注釋之后,再查詢,程序會(huì)自動(dòng)把這個(gè)關(guān)聯(lián)的數(shù)據(jù)給查出來,一并返回給前端。我這里做的是Restful接口。
2,新建記錄的時(shí)候,要設(shè)置parent_id值??墒羌恿岁P(guān)聯(lián)關(guān)系后,parent_id字段就消失了,沒辦法直接給這個(gè)字段賦值。也就沒辦法直接保存。
百度了半天也沒找到解決辦法。(說句題外話,現(xiàn)在網(wǎng)上的文章重復(fù)的太多,抄來抄去)
于是耍點(diǎn)小聰明,多建了一個(gè)與表單提交的數(shù)據(jù)格式對(duì)應(yīng)的類,強(qiáng)類型語言跟弱類型語言比,就是麻煩好多。好處就是嚴(yán)謹(jǐn)。用這個(gè)類來接收提交的數(shù)據(jù)。
再從中取得父分類的ID,去查一遍父分類,如果存在,就new一個(gè)父分類的實(shí)例出來,set到新記錄的Parent屬性里。
這時(shí)候現(xiàn)用這個(gè)數(shù)據(jù)去保存,jpa會(huì)幫你自動(dòng)給parent_id賦上值。
繞了一大圈。
3,實(shí)體類中加了關(guān)聯(lián)關(guān)系之后,repository中定義一個(gè)查詢,根據(jù)父ID,但其下的子分類。
這里自定義了一個(gè)方法:findAllByParentId
這里用了ParentId,不知道對(duì)不對(duì),更不知道后面會(huì)有什么樣的影響。
不管了,能用就行。
我這代碼雖然能起作用,可不一定正確。僅供參考!
到此這篇關(guān)于淺析JPA分類表的操作函數(shù)的文章就介紹到這了,更多相關(guān)JPA分類表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決idea中maven新增的配置文件xx.xml沒生效問題
這篇文章主要介紹了如何解決idea中maven新增的配置文件xx.xml沒生效問題,公司項(xiàng)目有用自己的`私服,Maven正常去私服下載jar包是沒問題的,但阿里云鏡像找不到相關(guān)的jar包報(bào)錯(cuò),文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06springboot實(shí)現(xiàn)rabbitmq消息確認(rèn)的示例代碼
RabbitMQ的消息確認(rèn)有兩種, 一種是消息發(fā)送確認(rèn),第二種是消費(fèi)接收確認(rèn),本文主要介紹了springboot實(shí)現(xiàn)rabbitmq消息確認(rèn)的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09Java?hibernate延遲加載get和load的區(qū)別
這篇文章主要介紹了Java?hibernate延遲加載get和load的區(qū)別,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09Ajax實(shí)現(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng)
這篇文章主要為大家詳細(xì)介紹了jQuery ajax實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能幫助到你2021-07-07spring boot多數(shù)據(jù)源動(dòng)態(tài)切換代碼實(shí)例
這篇文章主要介紹了spring boot多數(shù)據(jù)源動(dòng)態(tài)切換代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01RxJava中map和flatMap的用法區(qū)別源碼解析
這篇文章主要為大家介紹了RxJava中map和flatMap的用法區(qū)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09SpringBoot CountDownLatch多任務(wù)并行處理的實(shí)現(xiàn)方法
本篇文章主要介紹了SpringBoot CountDownLatch多任務(wù)并行處理的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決
這篇文章主要介紹了springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08