@JoinColumnsOrFormulas实现附属表的多字段查询
/** * 产品分类 * @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的声明对于附属表的级联更新就有了依据,数据就可以实现级联保存。
每天都是崭新的开始 ——Mr.司满(214382122)[]~( ̄▽ ̄)~*