Hibernate中视图的映射

本文介绍如何使用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() ;
	}
 

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值