Hibernate3 annotation many-to-one 的“高级用法”

关键的Image类
 
package amu.entity.test;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import amu.entity.IdEntity;
import amu.entity.user.User;

/** 
 * @{#} Image.java Create on 2009-2-16 下午08:00:48 
 * <p>
 *  
 * </p>
 * @author <a href="mailto:[email protected]">lichengzhou</a>   
 * @version v 0.1
 */
@Entity
@Table(name = "IMAGES")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Image<T> extends IdEntity {
	
	private String path;
		
	private Long resourceType;
	
	private T resource;

	@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
	@JoinColumn(name="RESOURCE_ID")
	public T getResource() {
		return resource;
	}

	public void setResource(T resource) {
		this.resource = resource;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Long getResourceType() {
		return resourceType;
	}

	public void setResourceType(Long resourceType) {
		this.resourceType = resourceType;
	}
}


User 类的关键代码如下
@Entity
@Table(name = "USERS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User extends IdEntity 	
 
         .......

	private Set<Image<User>> images;
	@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
	@JoinColumn(name="RESOURCE_ID")
	public Set<Image<User>> getImages() {
		return images;
	}

	public void setImages(Set<Image<User>> images) {
		this.images = images;
	}
}


Role 类的关键代码如下

@Entity
@Table(name = "ROLES")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role extends IdEntity {

         ......

	private Set<Image<Role>> images;
	@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
	@JoinColumn(name="RESOURCE_ID")
	public Set<Image<Role>> getImages() {
		return images;
	}

	public void setImages(Set<Image<Role>> images) {
		this.images = images;
	}
}


从上可见User和Role对Image的配置基本一致,只是在Image的泛型设置中配置了不同的值,
都可以实现和Image表的一对多(测试 是可能通过的)都能得到数据库中对映的值,但缺点也很明显,User表和Role表中如果有相同的数据,如都有ID为1的数据,那么它们都会得到相同的images集合。
如果你用的是oracle且User和Role都用的是同一个Sequence那么可以尝试下这个方法,因为两表的ID都是唯一的。

工作之余突发奇想,证实可行,但实用性不强,和大家分享下,仅供娱乐





你可能感兴趣的:(oracle,Hibernate,工作,cache)