/** * 產品分類 * @author simm */ @Entity @Table @Data @NoArgsConstructor @Where(clause = "is_deleted = 0") public class ProductCategory extends FullAuditedAggregateRoot { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 圖標 */ @OneToOne(cascade = CascadeType.REMOVE,fetch = FetchType.LAZY) @JoinColumnsOrFormulas(value = { @JoinColumnOrFormula(column = @JoinColumn(name="id",referencedColumnName = "refId",insertable = false,updatable = false)), @JoinColumnOrFormula(formula = @JoinFormula(value = "1",referencedColumnName = "refModule")), @JoinColumnOrFormula(formula = @JoinFormula(value = "1",referencedColumnName = "refType")), @JoinColumnOrFormula(formula = @JoinFormula(value = "1",referencedColumnName = "isAck")), }) private FileRecord icon; }
@JoinColumnOrFormula 的 column 屬性,用於設置主表與關聯表的主外鍵關聯關系,formula允許寫表達式(做多字段的常量查詢)。上述的JPA設置方式,相關與sql語句的關聯查詢,類似於
select file_record.* from product_category as a inner join file_record as b on a.id = b.ref_id and b.ref_module=1 and b.ref_type=1 and is_ack=1
事實上,JPA的查詢並不會因為我們設置了@JoinColumn而生成一個關聯查詢語句獲取實體,它是分兩次發起請求。
-- 1、先查詢主表 ---- select * from product_category where id = 3; -- 2、再查詢明細表 ------- select * from file_record where ref_id=3 and ref_module=1 and ref_type=1 and is_ack=1;
當然,這樣的做法對框架來說,取數是最方便的,不管與附屬表是OneToOne 還是 ManyToOne還是ManyToMany的關系,主實體的查詢永遠是一次檢索就能正確加載。不讀視圖就沒有主表信息重復的問題。對JPA來講,@JoinColumn的聲明對於附屬表的級聯更新就有了依據,數據就可以實現級聯保存。