一些领域我有两个实体与多对一(一对多)的关系。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教程,其中解释了这些概念 –