2012-01-23 93 views
1

我對hibernate很新穎。使用Hibernate註釋持久化數據

我有如下表:

合同

ContractID(PK), 其他列

提供商
ProviderID(PK), 其他列

ContractualAgreement ContractualAgreementID(PK), ContractID(FK), ProviderID(FK), 其他列

我使用以下休眠註釋:

**Contract.java** 

    { 

    private List<ContractualAgreement> contractualAgreements = new ArrayList<ContractualAgreement>(); 

    @OneToMany(cascade= { javax.persistence.CascadeType.ALL },fetch= FetchType.LAZY) 
    @JoinColumn (name="ContractID", updatable=false,insertable=false) 
    public List<ContractualAgreement> getContractualAgreements() { 
      return this.contractualAgreements; 
     } 
    } 

**Provider.java** 
{ 
    private List<ContractualAgreement> contractualAgreements = new  ArrayList<ContractualAgreement>(); 

    @OneToMany(cascade= { javax.persistence.CascadeType.ALL },fetch= FetchType.LAZY) 
    @JoinColumn (name="ProviderID", updatable=false,insertable=false,nullable=false) 
    public List<ContractualAgreement> getContractualAgreements() { 
      return this.contractualAgreements; 
     } 
    } 
} 

**ContractualAgreement.java** 
{ 
    @Id 
    @Column(name = "ContractualAgreementID", unique = true, nullable = false) 
    public long getContractualAgreementId() { 
     return this.contractualAgreementId; 
    } 

    public void setContractualAgreementId(long contractualAgreementId) { 
     this.contractualAgreementId = contractualAgreementId; 
    } 

    @ManyToOne(fetch= FetchType.LAZY) 
    @JoinColumn(name = "ProviderID",updatable=false,insertable=false,nullable=false) 
    public Provider getProvider() { 
     return this.provider; 
    } 

    public void setProvider(Provider provider) { 
     this.provider = provider; 
    } 

    @ManyToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="ContractID",updatable=false,insertable=false,nullable=false) 
    public Contract getContract() { 
     return this.contract; 
    } 
} 

我填充在以下順序數據:

  1. 契約對象契約契約對象。
  2. contractualagreements list on provider。

我嘗試使用saveOrUpdate保存提供程序。

現在它確實將提供者,contractualagreement表中的數據保存在contractualagreemtent表中的合適的提供者中,但不保存合同表中的數據。

任何人都可以指出我做錯了什麼?

任何幫助表示讚賞。

回答

0

你做錯了很多事情。

首先;合同協議表只是一個連接表。它沒有任何其他功能列,因此用於實現合同和提供者之間的關聯。此表從而

  • 沒有ID
  • 具有包含複合PK兩個FKS
  • 不能映射爲一個實體

你應該有合同和提供者之間的多對多關係。 ManyToMany關聯將使用ContractualAgreement表進行映射。

代碼中的其他問題:

  • 你標記的一切,insertable = false, updateable = false。如果沒有東西可以插入或更新,那麼這些列將如何填充?
  • OneToMany雙向關聯應該有許多側與JoinColumn映射。對方應該說:「這個協會已經映射到另一邊」,使用OneToMany(mappedBy = "thePropertyOnTheOtherSide")

所有這些在Hibernate參考手冊中都有詳細描述。 Read it

+0

感謝您的回覆,但contractualagreement表確實有其他列鏈接到其他表以及它自己的列。 –

+0

然後根據參考手冊正確映射您的雙向OneToMany。 –

相關問題