ORM--复合主键--Hibernate4.0注解版

实现复合主键的方法比较多,我一般采用如下方式。(当然了,能不使用复合主键就不使用)

Student类中,通过@EmbeddedId来指定主键是复合主键。

UserName类同时需要@Embeddable来标注。

Student类中不仅仅包含了复合主键,也包含了其他类型的属性,例如@Lob(通过使用Oracle10gR2来测试,并没有出现“no more data read from socket"的错误。)

复杂属性,也可以通过@Embeddable来进行标注。



@Entity
@Table(name="tmp_student")
public class Student implements Serializable {
	
	@EmbeddedId
	private UserName username;
	
	private Address address;
	
	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public UserName getUsername() {
		return username;
	}

	public void setUsername(UserName username) {
		this.username = username;
	}
	
	@Lob
	private byte []images;
	
	@Lob
	private String text;

	public byte[] getImages() {
		return images;
	}

	public void setImages(byte[] images) {
		this.images = images;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
	
	
	@Embeddable
	public static class Address implements Serializable{
		
		private String homeAddress;
		
		private String officeAddress;
		
		
		public String getHomeAddress() {
			return homeAddress;
		}
		public void setHomeAddress(String homeAddress) {
			this.homeAddress = homeAddress;
		}
		public String getOfficeAddress() {
			return officeAddress;
		}
		public void setOfficeAddress(String officeAddress) {
			this.officeAddress = officeAddress;
		}
		
	}
	
	
	@Embeddable
	public static class  UserName implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = -6684160391794613605L;
		
		private String first_name;
		private String last_name;
		public String getFirst_name() {
			return first_name;
		}
		public void setFirst_name(String first_name) {
			this.first_name = first_name;
		}
		public String getLast_name() {
			return last_name;
		}
		public void setLast_name(String last_name) {
			this.last_name = last_name;
		}
		
		@Override
		public boolean equals(Object object){
			if(object instanceof UserName){
				UserName userName=(UserName) object;
				return new EqualsBuilder().append(this.first_name, userName.getFirst_name())
										  .append(this.last_name, userName.getLast_name())
										  .isEquals();
			}
			else{
				return false;
			}
			
			
		}
		
		@Override
		public int hashCode(){
			//取任意素数17
			int result=17;
			result = 31*result +first_name.hashCode();
			result = 31*result +last_name.hashCode();
			return result;
		}
		
		
	}
}


你可能感兴趣的:(ORM--复合主键--Hibernate4.0注解版)