一、Customer中包含的字段:
private static final long serialVersionUID = 1L;
private Integer id;
private String sex;
private double salary;
private Double comm;
private String birth;
private Double total;
private String desc;
二、Hibernate配置文件
<class name="Customer" table="customers" catalog="hjd">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="sex" length="4"></property>
<property name="salary" />
<property name="comm"/>
<!-- 类中没有birth的get set 方法 -->
<property name="birth" type="date" access="field"/>
<!-- 映射Java持久化类中不存在的属性,只要用于HQL中,当数据库中有某列,二实体中不存在 -->
<property name="deptName" type="string" access="noop"/>
<property name="total" formula="(select c.salary+c.comm from customers c where c.id=id)"></property>
<property name="desc" column="`desc`"/>
</class>
三、测试
获得每个部门发出的工资总数
@Test
public void getObject() {
Session session = HiberSessionFactory.getSession();
/*Customer c=(Customer) session.get(Customer.class, 2);
System.out.println(c.getTotal());*/
@SuppressWarnings("unchecked")
List<Customer> list=session.createCriteria(Customer.class).add(Restrictions.eq("deptName", "军")).list();
int total=0;
for(Customer c:list){
total+=c.getTotal();
}
System.out.println(total);
HiberSessionFactory.closeSession();
}