Out*_*ast 5 java rest hibernate jpa
让我们假设一个 RESTful 服务收到一个PATCH请求来更新一个实体的一个或多个字段,这个实体可能有几十个字段。
@Entity
public class SomeEntity {
@Id
@GeneratedValue
private Long id;
// many other fields
}
Run Code Online (Sandbox Code Playgroud)
修补相应实体的一种肮脏方法是编写如下内容:
SomeEntity patch = deserialize(json);
SomeEntity existing = findById(patch.getId());
if (existing != null)
{
if (patch.getField1() != null)
{
existing.setField1(patch.getField1());
}
if (patch.getField2() != null)
{
existing.setField2(patch.getField2());
}
if (patch.getField3() != null)
{
existing.setField3(patch.getField3());
}
}
Run Code Online (Sandbox Code Playgroud)
但这太疯狂了!如果我想将 1 修补到该实体的许多和其他关联,则精神错乱甚至可能变得危险!
有没有一种理智的优雅方式来完成这项任务?
修改 SomeEntity 的 getter 并应用检查,如果任何值为空或 null,则返回相应的实体对象值。
class SomeEntity {
transient SomeEntity existing;
private String name;
public String getName(){
if((name!=null&&name.length()>0)||existing==null){
return name;
}
return existing.getName();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1322 次 |
| 最近记录: |