一些領域我有兩個實體與多對一(一對多)的關係。JPA實體之間的關係。如何使實體從DB只從關係表
類ParserEntity:
import javax.persistence.*;
@Entity
@Table(name = "parser", schema = "newsmonitoringdb")
public class ParserEntity {
public ParserEntity() {
}
public ParserEntity(String name, SourceTypesEntity type) {
this.name = name;
this.type = type;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Basic
@Column(name = "name")
private String name;
@ManyToOne(optional = false)
@JoinColumn(name="type",referencedColumnName="id")
private SourceTypesEntity type;
...//getters, setters and other fields are here
}
}
類ParserTypesEntity:
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
/**
* Created by User on 17.08.2016.
*/
@Entity
@Table(name = "source_types", schema = "newsmonitoringdb")
public class ParserTypesEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Basic
@Column(name = "name")
private String name;
@OneToMany(mappedBy="type", fetch=FetchType.EAGER, targetEntity = ParserEntity.class)
private Collection<ParserEntity> siteParser;
...//getters and setters are here
}
}
他們必須通過現場的關係,一切似乎確定。 但是我想要一個ParserTypeEntity類來保存ParserEntity類中的名字,而不是ParserEntity列表。
我希望它們在從數據庫檢索類型時自動填充,就像現在使用ParserEntity對象一樣。
有沒有辦法做到這一點,或者我必須將關係改爲單向函數,獲取所有類型,然後通過其id獲取每種類型的名稱?
它節省了您的模型(如所有JPA文檔所述)。修正你的模型,讓你有一個字符串集合,並填充它。 –
我試圖創建沒有「mappedBy」和「targerEntity」參數的OneToMany字段。我做了一個集合保存字符串參數,但是編譯器告訴OneToMany屬性值類型不應該是「String」 – Andrey
顯然'@ OneToMany'不應該用於...這是關係。你想要存儲需要'@ ElementCollection'的字符串集合!建議您閱讀JPA教程,其中解釋了這些概念 –