简体   繁体   English

Hibernate - 如何保留实体但忽略某些字段?

[英]Hibernate - How to persist an entity but disregarding certain fields?

I have an Entity with several fields:我有一个包含多个字段的实体:

@Entity
public class Leilighet {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long leilighetId;
private String navn;
private String beskrivelse;
private String adresse;
private String postNr;
private String postSted;
private double pris;

//The following fields should not be stored:
private String filename;
private String filetype;
private String filesize;
private byte[] filebin;

....
}

I have a corresponding form and Action that will populate this object and persist it to mySql.我有一个相应的表单和操作将填充此 object 并将其保存到 mySql。 This is all good when it comes to storing new "Leilighet"-entities.当涉及到存储新的“Leiliget”实体时,这一切都很好。

But when im using this form to "edit" an existing "Leilighet", I have stumbled upon something i cant figure out what to do.但是当我使用这个表格来“编辑”一个现有的“Leilighet”时,我偶然发现了一些我不知道该怎么做的事情。

For editing purposes i do not want to load the entire uploaded file.出于编辑目的,我不想加载整个上传的文件。 It is enough to just show the filename to indicate that there is a file present.仅显示文件名以表明存在文件就足够了。 If the user chooses a new File then it should be overwritten, but if the user chooses nothing then the present file should be kept.如果用户选择了一个新文件,那么它应该被覆盖,但如果用户什么都不选择,那么应该保留当前文件。

But I cant figure out how to make hibernate do what i want.但我不知道如何让 hibernate 做我想做的事。 Unless i populate the filebin with the actual file, hibernate will just delete the file.除非我用实际文件填充filebin ,否则 hibernate 只会删除该文件。

How can I tell hibernate to just update the other fields and not the filefields?我如何告诉 hibernate 只更新其他字段而不是文件字段?

Hibernate supports loading individual properties lazily. Hibernate 支持懒加载单个属性。 See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#performance-fetching-lazyproperties for details.有关详细信息,请参阅http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#performance-fetching-lazyproperties

Or you could just use a DTO with only the fields you want in this specific use-case, and execute a query with the appropriate projections in order to populate this DTO from the database.或者,您可以只使用仅包含此特定用例中所需字段的 DTO,并使用适当的投影执行查询,以便从数据库中填充此 DTO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM