我有一个映射到特定表中的行的 POJO。该行描述了某个站点中的图像,并包含宽度、高度、url、某种状态和其他一些字段等数据。在一些遗留代码中,我有一个返回 url 和状态的查询(在 hibernate
中)。此数据封装在类 ImageStatusAndOrigFilename
中。
我认为这是一个坏主意,因为:
- 如果明天我需要查询其他一些字段怎么办?该名称与数据的耦合度太高。
- 过去获取图像宽度和高度的唯一方法是解析 url。今天我们在数据库中映射宽度和高度,因此我现在需要获取图像大小和状态(并且我不再关心原始文件名)。所以我需要更改这个类,但不能,因为它正在代码中的其他地方使用。我希望得到一些更通用的东西,不与特定场景耦合,并且可以在需要时进行扩展。
我正在尝试找出要使用的数据结构。我是否应该使用具有所有字段但将其中一些字段保留为空的原始 POJO(我不想查询所有字段,因为在这种情况下我不需要所有字段)。我应该为这个特定查询创建另一个 POJO(当然有更好的名称)?
当然也欢迎任何其他建议。
编辑:
POJO:
@Entity
@Table(name = "web_image")
public class WebImage {
private long id;
private Document document;
private Integer mediaType;
private Integer width;
private Integer height;
private Date creationDate;
private Date modificationDate;
private String origUrl;
private ImageStatus status;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long getId() {
return id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "document_id")
public Document getDocument() {
return document;
}
public void setDocument(final OBDocument document) {
this.document = document;
}
@Column(name = "width")
public Integer getWidth() {
return width;
}
public void setWidth(final Integer width) {
this.width = width;
}
// Other getters and setters for the rest of the private fields
}
查询:
SELECT b.document_id , b.status , b.orig_file_id, a.min_id as id FROM web_image b, ( SELECT x.document_id, MAX(x.id) max_id, MIN(x.id) min_id FROM web_image x WHERE x.document_id in ( :docs ) GROUP BY x.document_id) a WHERE a.max_id = b.id
最佳答案
这个怎么样:
@MappedSuperclass
public class ImageStatusAndOrigFilename {
...
}
@Entity
public class WebImage extends ImageStatusAndOrigFilename {
...
}
现在你有了两个类,旧的不是一个实体,但它的客户端对此一无所知,所有的获取和持久都在 WebImage
类上,但你可以查询ImageStatusAndOrigFilename
。
关于java - 封装仅从 Hibernate 查询返回部分数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19832616/