我有Spring Data JPA的Spring启动应用程序。 我想创建接受外键实体id的构造函数,而不是实体对象。
我发现我可以使用来自Hibernate的session.load(Source.class,sourceId)(它甚至不会向数据库提出额外的请求,正是我需要的),但我不知道如何在实体中使用它
有可能吗?处理这个问题的最佳做法是什么?
以下示例说明了我想要的内容。
@Entity
public class Article implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private int id;
@JsonProperty(value = "source")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "source_id", nullable = false)
private Source source;
@Column(name = "title", nullable = false)
private String title;
@Column(name = "description", nullable = false)
private String description;
public Article() {
}
// existing constructor
public Article(Source source, String title, String description) {
this.source = source;
this.title = title;
this.description = description;
}
// constructor that I need
public Article(Integer sourceId, String title, String description, Integer sourceId) {
this.source = sourceId; // some magic should be here
this.title = title;
this.description = description;
}
}