淺析JPA分類表的操作函數
這里說的分類表是指一般系統(tǒng)中用到的分類管理的表。
結構如下:
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;
實體類,如下 :
@Entity
@DynamicUpdate
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
// 為了設置關聯(lián)關系,需要注釋掉.
// 反正這里沒搞明白,沒設關聯(lián)關系前,設了Column()返回的數據中字段不對了。
// 這里后面再研究吧
// 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 代碼
// 關聯(liá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;
}這個類是為了新建記錄時用的。別問為什么,我自己研究出來的,因為我不知道還有其它什么好辦法。
1,前端需要一個列表,顯示:父類名稱 +當前分類的信息。
由于記錄中只有一個parent_id來關聯(lián)父分類,所以用sql的寫法就是寫個left join就好了。把要查的查出來。這種事交給php那是非常簡單。
Java不行啊,尤其是JPA。
查了查文檔,設置關聯(lián)關系可能是比較優(yōu)雅的方式。
所以,有了實體類中的@ManyToOne的注釋,因為加了這個屬性,原先的parent_id字段就得隱藏。這里太明白為什么,留待以后研究。
加了關聯(lián)注釋之后,再查詢,程序會自動把這個關聯(lián)的數據給查出來,一并返回給前端。我這里做的是Restful接口。
2,新建記錄的時候,要設置parent_id值。可是加了關聯(lián)關系后,parent_id字段就消失了,沒辦法直接給這個字段賦值。也就沒辦法直接保存。
百度了半天也沒找到解決辦法。(說句題外話,現在網上的文章重復的太多,抄來抄去)
于是耍點小聰明,多建了一個與表單提交的數據格式對應的類,強類型語言跟弱類型語言比,就是麻煩好多。好處就是嚴謹。用這個類來接收提交的數據。
再從中取得父分類的ID,去查一遍父分類,如果存在,就new一個父分類的實例出來,set到新記錄的Parent屬性里。
這時候現用這個數據去保存,jpa會幫你自動給parent_id賦上值。
繞了一大圈。
3,實體類中加了關聯(lián)關系之后,repository中定義一個查詢,根據父ID,但其下的子分類。
這里自定義了一個方法:findAllByParentId
這里用了ParentId,不知道對不對,更不知道后面會有什么樣的影響。
不管了,能用就行。
我這代碼雖然能起作用,可不一定正確。僅供參考!
到此這篇關于淺析JPA分類表的操作函數的文章就介紹到這了,更多相關JPA分類表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決idea中maven新增的配置文件xx.xml沒生效問題
這篇文章主要介紹了如何解決idea中maven新增的配置文件xx.xml沒生效問題,公司項目有用自己的`私服,Maven正常去私服下載jar包是沒問題的,但阿里云鏡像找不到相關的jar包報錯,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-06-06
Java?hibernate延遲加載get和load的區(qū)別
這篇文章主要介紹了Java?hibernate延遲加載get和load的區(qū)別,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
RxJava中map和flatMap的用法區(qū)別源碼解析
這篇文章主要為大家介紹了RxJava中map和flatMap的用法區(qū)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
SpringBoot CountDownLatch多任務并行處理的實現方法
本篇文章主要介紹了SpringBoot CountDownLatch多任務并行處理的實現方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
springboot啟動feign項目報錯:Service id not legal hostnam的解決
這篇文章主要介紹了springboot啟動feign項目報錯:Service id not legal hostnam的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

