使用方法
private Long usersSize;
@Formula("(id * 8888888)")
@JsonProperty
public Long getUsersSize(){
return usersSize;
}
public void setUsersSize(Long usersSize) {
this.usersSize = usersSize;
}
略。。。。
注意 必须使用()来包裹sql片段,hibernate不会在数据库创建userSize对应的列
查看下生成的hibernate 生成的 sql,很明显是在数据库做了运算
select agent0_.id as id1_, agent0_.acl_code as acl2_1_, agent0_.acl_type as acl3_1_, agent0_.created_by
as created4_1_, agent0_.created_dt as created5_1_, agent0_.updated_by as updated6_1_, agent0_.updated_dt
as updated7_1_, agent0_.version as version1_, agent0_.agent_addres as agent9_1_, agent0_.agent_city
as agent10_1_, agent0_.agent_county as agent11_1_, agent0_.agent_name as agent12_1_, agent0_.agent_province
as agent13_1_, agent0_.agent_scale as agent14_1_, agent0_.zip_code as zip15_1_, agent0_.biz_lic_reg_no
as biz16_1_, agent0_.join_date as join17_1_, agent0_.oper_org_type as oper18_1_, agent0_.org_code_cert_no
as org19_1_, (agent0_.id * 8888888) as formula0_ from agent_agent agent0_ order by agent0_.created_dt
desc limit 15
甚至你可以这样玩:
查询该代理下用户总数
@Formula("(select count(*) from tbl_auth_user o where o.agent_id = id)")
id 代表当前表的id
@Formula("(select count(*) from tbl_auth_user o where o.agent_id = id)")
@JsonProperty
public Long getUsersSize(){
return usersSize;
}
hibernate生成的 sql
select agent0_.id as id1_, agent0_.acl_code as acl2_1_, agent0_.acl_type as acl3_1_, agent0_.created_by
as created4_1_, agent0_.created_dt as created5_1_, agent0_.updated_by as updated6_1_, agent0_.updated_dt
as updated7_1_, agent0_.version as version1_, agent0_.agent_addres as agent9_1_, agent0_.agent_city
as agent10_1_, agent0_.agent_county as agent11_1_, agent0_.agent_name as agent12_1_, agent0_.agent_province
as agent13_1_, agent0_.agent_scale as agent14_1_, agent0_.zip_code as zip15_1_, agent0_.biz_lic_reg_no
as biz16_1_, agent0_.join_date as join17_1_, agent0_.oper_org_type as oper18_1_, agent0_.org_code_cert_no
as org19_1_, (select count(*) from tbl_auth_user o where o.agent_id = agent0_.id) as formula0_
from agent_agent agent0_ order by agent0_.created_dt desc limit 15
更多用例
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
@Formula("(select max(o.creation_date) from Orders o where o.customer_id = id)")
private Date lastOrderDate;
@Formula("(select coalesce(extract ('day' from age(max(o.creation_date))), 9999) from Orders o where o.customer_id = id)")
private int daysSinceLastOrder;
@Formula (公式)虽好,但是不要滥用哦