Hibernate联合主键

Hibernate联合主键:

1.主键类UserId实现Serializable接口,重写hashCode()和equals()方法,使用@Embeddable注解修饰

 

package com.jin.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class UserId implements Serializable {
	private String firstName;
	private String lastName;
	
	@Column(name="first")
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	
	@Column(name="last")
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UserId other = (UserId) obj;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		return true;
	}
	
}

 

2.实体类User

主键变量用@EmbeddedId注解修饰

@AttributeOverride(name="firstName", column=@Column(name="fld_firstname"))

将主键类UserId中变量firstName所对应列名重新命名为fld_firstname

package com.jin.domain;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class User {
	private UserId id;
	private Integer age;
	
	@EmbeddedId
	//重写firstName变量在数据库表中所对应的列名
    @AttributeOverride(name="firstName", column=@Column(name="fld_firstname"))
	public UserId getId() {
		return id;
	}
	public void setId(UserId id) {
		this.id = id;
	}
	
	@Column
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

 3.自动生成的数据库表

主键是fld_firstname,last联合主键,firstname的列名有我们自定义的first被替换为fld_firstname
Hibernate联合主键_第1张图片
 5.xml配置

<class name="User">
   <composite-id name="id" class="UserId">
      <key-property name="firstName" column="fld_firstname"/>
      <key-property name="lastName"/>
   </composite-id>
</class>

 

 

你可能感兴趣的:(Hibernate)