查询结果:
select
students0_.id as id0_,
students0_.name as name0_,
students0_.sex as sex0_,
students0_.number as number0_,
(select
count(*)
from
T_Books ) as formula0_
from
T_Students students0_
where
students0_.name=‘liu‘
name : liu
number : 006
bookCount : 2
从hibernate执行的语句中,我们可以看到Students的bookCount属性是formula通过执行指定的"select count(*) from T_Books"来获得的,bookCount字段在数据库表T_Students表中是没有的,它是一个虚拟列。
@Formula注解
@Formula("(select COUNT(*) from user)")
private int count;
注意
<property name="belongOrganN" type="string" insert="false" update="false" formula="(select x.OrganShortN from tsy_organ x where x.OrganID= BelongOrganID)"/> 或
<property name="belongOrganN" type="string" insert="false" update="false">
<formula><![CDATA[(select x.OrganShortN from tsy_organ x where x.OrganID= BelongOrganID)]]></formula>
</property>
formula="()",里面的是sql语句,字段和表名都应该和数据库相对应,若带有参数如(select x.OrganShortN from tsy_organ x where x.OrganID= BelongOrganID),OrganID是tsy_organID表中的字段,BelongOrganID名称表示当前<property>元素所在的映射文件对应表的字段名。
formula="( sql )",这个括号不能少,不然会报错,我试了几次,没括号就报错,添上就没问题。如:
@Formula("(select x.OrganShortN from tsy_organ x where x.OrganID= BelongOrganID)")
注意该属性与<union-subclass>标签的位置有关,若 <union-subclass>标签作为<class>标签的子标签,则"extends"属性可以不设置,否则需要明确设置"extends"属性。<class>标签中的"abstract"属性如果值为true则不会生成people表结构;如果值为false则会生成people表结构,但是不能向people表插入数据。(如果没有指定table属性的值则生成的表名为类名的第一个字母小写的)根据 People.hbm.xml生成表结构:
drop table if exists student
drop table if exists teacher
create table student (
id varchar(255) not null,
name varchar(255),
sex varchar(255),
age varchar(255),
birthday datetime,
cardId varchar(255),
primary key (id)
)
create table teacher (
id varchar(255) not null,
name varchar(255),
sex varchar(255),
age varchar(255),
birthday datetime,
salary integer,
primary key (id)
)
根据 People.hbm.xml生成表结构:
drop table if exists people
create table people (
id varchar(255) not null,
peopleType varchar(255) not null,
name varchar(255),
sex varchar(255),
age varchar(255),
birthday datetime,
cardId varchar(255),
salary varchar(255),
primary key (id)
)
可以看到一张表将继承体系下的所有信息都包含了,其中"peopleType"为标识列。
*********************
<property>元素的type (optional)属性,它可以取值为hibernate type和java type:
Java Class Attribute Type Hibernate Type Possible SQL Type-Vendor Specific
Integer, int, long short integer, long, short Appropriate SQL type
*****************
也可以在hbm.xml文件中配置命名查询:
<hibernate-mapping>
<class>......</class>
<query name="findGroupsByUser">
<![CDATA[
select distinct g
from org.jbpm.pvm.internal.identity.impl.MembershipImpl m
join m.user u
join m.group g
where u.id = :userId
]]>
</query>
</hibernate-mapping>
Query query = session.getNamedQuery("findGroupsByUser");
query.setInteger("userId", 25);
List result= query.list();