簡體   English   中英

在成員變量或實體的get方法處設置JPA注釋?

[英]Set JPA Annotations at the member variable or at get methods of an entity?

我沒有關於JPA和Hibernate的豐富經驗。 對我來說,尚不清楚,何時有必要在我可以將get方法用於注釋時,在我的實體類的成員變量處編寫JPA注釋。 是不是應該在實體的set方法中設置注釋? 這是一個小例子:

public class MessageEntity implements Persistable{

    @ManyToOne
    StatusEntity state;

    @Column(nullable = false)
    private Boolean freitext = false;

    private Collection<Variables> variables;

    @OneToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST }, targetEntity = Variables.class)
    public Collection<Variables> getVariables() {
       return this.variables;
    }
}

我還不清楚何時必須使用屬性targetEntity。 有人可以幫我解釋一下嗎?

MAIK

批注可以在properties or the getters ,但不能在setter上。

在一對多關系中,如果指定的Set(collection)沒有泛型,則需要targetEntity。 如果使用Set <Generic>,則不需要targetEntity。

參考: Java API

我沒有在getter方法上使用任何JPA批注,我假設其與頂部的變量批注相同。 為了更簡潔,我將所有注釋都保留在變量的頂部。

對於我的@OneToMany上的“ targetEntity”屬性,我還沒有使用過,但是在使用@OneToMany時,我確實使用了appedBy。 我認為您不需要使用targetEntity。

@Entity
@Table(name="message_entity")
public class MessageEntity implements Persistable{

@ManyToOne
StatusEntity state;

@Column(nullable = false)
private Boolean freitext = false;

@OneToMany(mappedBy="message_entity"), cascade = { CascadeType.MERGE, CascadeType.PERSIS
private Collection<Variables> variables;

public Collection<Variables> getVariables() {
       return this.variables;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM