Hibernate中视图的映射

一、数据库已经建立视图,hibernate只是把视图当作普通的表来映射。

(略)

二、数据库没有视图,用hibernate自己做视图映射

 

配置文件MyView.xml

 

<class name="cn.cooler.vo.MyView">
	<!-- 列别名对应视图中的字段 -->
	<subselect>
		<![CDATA[
			select c.name n1, o.name n2
			from Customer c, Orders o
		]]>
	</subselect>
	<!-- 定义这个实体用到的表为同步,确保自动刷新,查询不会返回过期数据 -->
	<synchronize table="customer"/>
	<synchronize table="orders"/>
	<composite-id>
		<key-property name="n1"></key-property>
		<key-property name="n2"></key-property>
	</composite-id>
</class>

 

 

实体类MyView.class

 

package cn.cooler.vo ;

public class MyView implements java.io.Serializable {

	private static final long serialVersionUID = -7576276623426772936L ;
	private String n1 ;
	private String n2 ;
	
	public String getN1() {
		return n1 ;
	}
	public void setN1(String n1) {
		this.n1 = n1 ;
	}
	public String getN2() {
		return n2 ;
	}
	public void setN2(String n2) {
		this.n2 = n2 ;
	}
	@Override
	public boolean equals(Object other) {
		if (this == other) return true;
		if (!(other instanceof MyView)) return false;
		
		final MyView castOther = (MyView) other;

		return 	((this.getN1() == castOther.getN1() 
				|| (this.getN1() != null && castOther.getN1() != null 
					&& this.getN1().equals(castOther.getN1()))))
			&& 
				((this.getN2() == castOther.getN2() 
				|| (this.getN2() != null && castOther.getN2() != null 
					&& this.getN2().equals(castOther.getN2())))) ;
	}
	@Override
	public int hashCode() {
		int result = 17;
		result = 37 * result
				+ (getN1() == null ? 0 : this.getN1().hashCode());
		result = 37 * result
				+ (getN2() == null ? 0 : this.getN2().hashCode());
		return result;
	}
	
}

 单元测试通过:

 

@org.junit.Test
	public void view() {
		Session s = HibernateSessionFactory.getSession() ;
		List l = s.createQuery("From MyView v").list() ;
		for(Object o : l) {
			MyView v = (MyView) o ;
			System.out.println(v.getN1() + " " + v.getN2()) ;
		}
		s.close() ;
	}
 

 

 

 

你可能感兴趣的:(C++,c,Hibernate,JUnit,单元测试)