1. 程式人生 > >Hibernate處理沒有主鍵的檢視

Hibernate處理沒有主鍵的檢視

  1. 檢視的詳情

SELECT TEST_FLIGHT_TIME AS TESTTIME,JIHAO AS JIHAO,'1' AS TYPE,FP_ID,REF_ID FROM S_FLIGHT_PLAN -- 1:主機檢查時間

UNION

SELECT INSPECT_TIME AS TESTTIME,JIHAO AS JIHAO,'2' AS TYPE,FP_ID,REF_ID FROM S_FLIGHT_PLAN -- 2:主機試飛時間

UNION

SELECT TEST_FLIGHT_TIME1 AS TESTTIME,STANDBY_PLANE AS JIHAO,'3' AS TYPE,FP_ID,REF_ID FROM S_FLIGHT_PLAN -- 3:備份機檢查時間

UNION

SELECT INSPECT_TIME1 AS TESTTIME,STANDBY_PLANE AS JIHAO,'4' AS TYPE,FP_ID,REF_ID FROM S_FLIGHT_PLAN -- 4:備份機試飛時間 -- 試飛時間,試飛機號,試飛型別,飛行任務id,派遣任務id

a) 本檢視中使用了TSETTIME,JIHAO,TYPE,FP_ID,REF_ID五個欄位,由於每個欄位都不是唯一的,所以沒有主鍵

  1. 由於hibernate處理所有資料,基本都是要有主鍵的,所以在按建立實體類的時候,會有麻煩,有了下邊的解決方法.
  2. 新建一個主鍵類,用幾個屬性作為聯合主鍵,用@Embeddable註解修飾,將幾個屬性放入進來,寫入get,set方法,並且重寫equals()和hashCode()方法.
@Embeddable 
public class VTestFlightKey implements Serializable { 

private static final long serialVersionUID = 1L;

private Date TESTTIME;

/**

JIHAO 機號 / 
private String JIHAO; 
/*
TYPE */ 

private String TYPE; 

/*
FP_ID 飛行計劃id */

private String FP_ID;
private String REF_ID;

public String getREF_ID() {
	return REF_ID;
}


public void setREF_ID(String rEF_ID) {
	REF_ID = rEF_ID;
}


public String getFpid() {
	return FP_ID;
}


public void setFpid(String fpid) {
	this.FP_ID = fpid;
}


public Date getTestTime(){
	return TESTTIME;
}


public void setTestTime(Date testTime){
	this.TESTTIME=testTime;
}

public String getJihao(){
   return JIHAO;
}	

public void setJihao(String jihao){
	this.JIHAO=jihao;
}

public String getType(){
	return TYPE;
}


public void setType(String type){
	this.TYPE=type;
}
@Override  
public int hashCode() {  
  return this.TESTTIME.hashCode();
}

@Override
public boolean equals(Object o) {
  if(o instanceof VTestFlightKey){
     VTestFlightKey key = (VTestFlightKey)o ;
     if(this.TESTTIME.equals(key.getTestTime()) && this.JIHAO.equals(key.getJihao()) && 
      this.TYPE.equals(key.getType()) && this.FP_ID.equals(key.getFpid()) && 
      this.REF_ID.equals(key.getREF_ID())){
        return true ;
    }
  }
  return false ;
 }
}





將主鍵類,作為主類的ID屬性,並用@Id註解修飾,且主鍵類中已經用來做聯合主鍵的屬性,不再寫在主類中,

@Entity 

@Table(name="V_TEST_FLIGHT") 

public class VTestFlight{ 

    private static final long serialVersionUID = 1L; //由於所有欄位用用來做聯合主鍵,所以欄位都在主鍵類VTestFlightKey 

    @Id 

    private VTestFlightKey vTestFlightKey; 

    public VTestFlightKey getvTestFlightKey() { 

            return vTestFlightKey; 

    }

    public void setvTestFlightKey(VTestFlightKey vTestFlightKey) {

         this.vTestFlightKey = vTestFlightKey;