1.数据库已经建立视图,hibernate只是把视图当作普通的表来映射。
视图VIEW_MER_INST_POS: select MER.DAYS_MERCHT_ID MER_ID, INST.DAYS_MERCHT_ID INST_ID, POS.POS_ID POS_ID from tbl_days_mercht_attr MER, tbl_days_mercht_info INST, tbl_days_mercht_pos_info POS where MER.days_mercht_id = INST.up_days_mercht_id and INST.days_mercht_id = POS.days_mercht_id hbm.xml配置 <class name="db.po.ViewMerInstPos" table="VIEW_MER_INST_POS" > <composite-id> <key-property name="merId" column="MER_ID" type="java.lang.String" length="8" /> <key-property name="instId" column="INST_ID" type="java.lang.String" length="8" /> <key-property name="posId" column="POS_ID" type="java.lang.String" length="8" /> </class> </hibernate-mapping>2.数据库没有视图,用hibernate自己做视图映射hibernate还允许把只读的实体映射到一个数据库的子查询中。当你想用视图代替一张基本表的时候,这是有用的。
2.1运用标签
<subselect> </subselect>
2.2 举例
数据库存在学生基本信息表,现在想建立一个视图来统计每个年龄段的学生人数,并用一个实体类的进行映射。
(1)学生信息表的的映射文件(Student.hbm.xml)如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" ""> <hibernate-mapping package="com.zds.domain"> <class name="Student" table="student" > <id name="id" column="student_id"> <generator class="native"/> </id> <property name="name"/> <property name="age"/> <property name="birthday"/> <property name="grade"/> </class> </hibernate-mapping>
(2)学生统计信息配置文件(StudentStatic.hbm.xml)如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" ""> <hibernate-mapping package="com.zds.domain"> <class name="StudentStatic" entity-name="studentStatic"> <subselect> select count(student.student_id) as student_num, student.age as student_age from student as student group by age </subselect> <synchronize table="student"/> <composite-id> <key-property name="age" column="student_age" type="int" /> </composite-id> <property name="student_num" column="student_num" type="int"/> </class> </hibernate-mapping>
【其中synchronize表示当表的数据发生变化的时候,视图的数据也会发生变化。】
(3)学生统计信息实体类(StudentStatic.java)定义如下:
package com.zds.domain;
import java.io.Serializable;
public class StudentStatic implements Serializable{ private int age; private int student_num; public int getStudent_num() { return student_num; } public void setStudent_num(int student_num) { this.student_num = student_num; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
现在查询视图,打印出学生统计信息:
List<StudentStatic> studentStaticData = new ArrayList<StudentStatic>(); Session session = null; Transaction tx = null; session = HibernateUtil.getSession(); tx = session.beginTransaction(); Query query = session.createQuery("from studentStatic"); studentStaticData = (List<StudentStatic>) query.list(); tx.commit(); for(StudentStatic studentStatic:studentStaticData) { System.out.println("年龄: "+studentStatic.getAge()+"
人数:"+studentStatic.getStudent_num()); }