淺析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那是非常簡(jiǎn)單。
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值。可是加了關(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)文章
Spring6當(dāng)中獲取Bean的四種方式小結(jié)
Spring 為Bean 的獲取提供了多種方式,通常包括4種方式,(也就是說在Spring中為Bean對(duì)象的創(chuàng)建準(zhǔn)備了多種方案,目的是:更加靈活),本文將通過代碼示例詳細(xì)的給大家介紹了一下這四種方式,需要的朋友可以參考下2024-04-04
基于Retrofit+Rxjava實(shí)現(xiàn)帶進(jìn)度顯示的下載文件
這篇文章主要為大家詳細(xì)介紹了基于Retrofit+Rxjava實(shí)現(xiàn)帶進(jìn)度顯示的下載文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
springmvc使用JSR-303進(jìn)行數(shù)據(jù)校驗(yàn)實(shí)例
本篇文章主要介紹了詳解springmvc使用JSR-303進(jìn)行數(shù)據(jù)校驗(yàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02
詳解Java中的checked異常和unchecked異常區(qū)別
這篇文章主要介紹了詳解Java中的checked異常和unchecked異常區(qū)別,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02
java生成excel并導(dǎo)出到對(duì)應(yīng)位置的方式
這篇文章主要介紹了java生成excel并導(dǎo)出到對(duì)應(yīng)位置的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
一文徹底弄懂Java中MultipartFile接口和File類
MultipartFile是一個(gè)接口,我們可以理解為是Spring?給我們綁定的一個(gè)在使用文件上傳等時(shí)簡(jiǎn)便實(shí)現(xiàn)的口子,這篇文章主要給大家介紹了關(guān)于如何通過一文徹底弄懂Java中MultipartFile接口和File類的相關(guān)資料,需要的朋友可以參考下2023-11-11
SpringBoot使用ip2region獲取地理位置信息的方法
這篇文章主要介紹了SpringBoot使用ip2region獲取地理位置信息的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06

