我是物體框架的新手,如果這看起來很愚蠢,請原諒我。
考慮以下 json 物件:
{
"id": "8850a2d2-230e-8ecb-cbb8-06068df136aa",
"fiscalCode": "QHNMPN27E68F765S",
"role": {
"id": "MED",
"name": "Medico di base"
},
"enabled": true,
"name": "Alessio",
"surname": "De Padova",
"contacts": [],
"specs": [
{
"name": "Fisiatria",
"id": "FISIA"
},
{
"name": "Cardiologia",
"id": "CARD"
}
],
"account": {
"id": "5541",
"email": "[email protected]"
},
"submit": null
}
假設我們將其作為請求正文發送,以便在資料庫中更新它。它是一個具有子物體的用戶,如下所示:
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Column(name = "name")
@NotNull(message = "Name cannot be null")
@Size(min = 1, message = "Name is not long enough")
private String name;
@Column(name = "fiscal_code")
@NotNull(message = "Fiscal code cannot be null")
@Size(min=16, max=16, message = "Fiscal code has to be 16 chars long")
private String fiscalCode;
@Column(name = "enabled")
private Boolean enabled;
@Column(name = "surname")
@Size(min = 1, message = "Surname is not long enough")
@NotNull(message = "Surname cannot be null")
private String surname;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "account_id")
private AccountEntity account;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "role_id")
private RoleEntity role;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private Set<ContactEntity> contacts;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "users_specs",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "spec_id")
)
private Set<SpecEntity> specs;
現在,問題來了。雖然我希望用戶物體能夠創建新帳戶(或聯系人)或更新現有帳戶(就像現在發生的那樣),但我不希望規范發生同樣的情況。用戶只能添加或洗掉規范,它無權創建新規范或更改規范的屬性。
配置這種行為的正確方法是什么?
以下代碼顯示了我想主要使用配置做什么:
userEntity.setSpecs(
userEntity
.getSpecs()
.stream()
.map(spec -> specSvc.get(spec.getId()))
.collect(Collectors.toSet())
);
What I am doing right there is "correcting" each spec entity that is sent by the client. By correcting, I mean preventing name (or any other kind of property) change so that the user can only add or remove specs. But cannot update them or create them. If the server receives a spec not containing an id, it will throw an error
uj5u.com熱心網友回復:
一般來說,不要讓用戶直接發布您的物體。無論如何,這將導致未來各種不同的問題。僅在您的示例中,如果用戶客戶端可以設定資料庫 ID,這將是不常見的。如果您曾經讓用戶更新他們自己的帳戶,您可能不希望他們能夠設定角色。
我會創建一些 DTO 物件,然后手動映射或使用一些映射器將它們映射到 JPA 物體。
在考慮可擴展性和可測驗性的同時,如何將域物體正確轉換為 DTO中有一些不同的方法(盡管這與您的情況相反),我在那里鏈接到我自己的答案,但有多種選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417335.html
標籤:
上一篇:SpringFox問題
下一篇:如何修復無法延遲初始化集合
