hibernate聯合主鍵

1、 hibernate聯合主鍵類的規則 java

      1. 實現Serializable接口 數據庫

      2. 重寫hashCodeequals方法 this

2、hibernate聯合主鍵的實體類規則緣由(與上面規則順序對應) spa

     1. Hibernate要根據數據庫的聯合主鍵來判斷某兩行記錄是不是同樣的,若是同樣那麼就認爲是同一個對象,若是不同,那麼就認爲是不一樣的對象。這反映到程序領域中就是根據hashCode與equals方法來判斷某兩個對象是否可以放到諸如Set這樣的集合當中; hibernate

     2. 使用get或load方法的時候須要先構建出來該實體的對象,而且將查詢依據(聯合主鍵)設置進去,get或load方法的第二個參數須要序列化。 code

public Object get(Class clazz,Serializable id)


3、 hibernate聯合主鍵的使用   xml

PrimaryKey.java 對象

public class PrimaryKey implements Serializable{  
    // 屬性
    private String cardID;  
    private String name;  
    //get、set方法省略
    ...
    // 重寫EQUAL方法
    public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof PrimaryKey))
			return false;
		PrimaryKey castOther = (PrimaryKey) other;
		return ((this.getCardID() == castOther.getCardID()) || (this.getCardID() != null && castOther.getCardID() != null && this.getCardID().equals(castOther.getCardID())))&& ((this.getName() == castOther.getName()) || (this.getName() != null && castOther.getName() != null && this.getName().equals(castOther.getName())));
   }

	 // 重寫HASHCODE方法
	public int hashCode() {
		int result = 17;
		result = 37 * result + (getSpId() == null ? 0 : this.getSpId().hashCode());
		result = 37 * result + (getName() == null ? 0 : this.getName().hashCode());
		return result;
	}  
}
Student.java
public class Student  {
    // 屬性
    private PrimaryKey primaryKey;  // 聯合主鍵類  
    private int age;      
    //set、get方法省略  
}

Student.hbm.xml 接口

<class name="bean.Student" table="student">  
    <!--PrimaryKey爲自定義的主鍵類-->
    <composite-id name="primaryKey" class="bean.PrimaryKey">  
       <!--name及cardID爲PrimaryKey類中的屬性-->
       <key-property name="name" column="student_name" type="string"></key-property>  
       <key-property name="cardID" column="card_id" type="string"></key-property>  
    </composite-id>  
    <property name="age" column="student_age" type="int"></property>  
</class>
hibernate中使用
// 獲取
	public Student get(Serializable id) throws Exception {
		Object obj = this.getHibernateTemplate().get(Student.class,id);
		if (obj == null) {
			return null;
		} else {
			return (Student) obj;
		}
	}
相關文章
相關標籤/搜索