Java 仅使用传入对象的非空属性更新实体
我有一个包含多个字段的实体类型。其中一些是对其他实体的引用。我想在Spring中创建一个RESTAPI端点,允许用户更新这种类型的实体 假设我有一个实体Java 仅使用传入对象的非空属性更新实体,java,spring,hibernate,Java,Spring,Hibernate,我有一个包含多个字段的实体类型。其中一些是对其他实体的引用。我想在Spring中创建一个RESTAPI端点,允许用户更新这种类型的实体 假设我有一个实体User,其中包含朋友列表。我只想让用户更新用户实体的一些特定字段,例如名称、年龄和描述,而不是朋友列表 此外,我只希望更新实体的那些属性,使相应的传入值不为null public class UserController { @RequestMapping(path="",method=RequestMethod.PUT) pu
User
,其中包含朋友列表。我只想让用户更新用户实体的一些特定字段,例如名称
、年龄
和描述
,而不是朋友列表
此外,我只希望更新实体的那些属性,使相应的传入值不为null
public class UserController {
@RequestMapping(path="",method=RequestMethod.PUT)
public void update(@RequestBody User user) {
userService.save(user);
}
}
我怎样才能做到这一点 在
update()
方法中,您可以使用只定义需要更改的属性的类,而不是将User
对象作为参数
像这样定义一个类UpdateUserDTO
public class UpdateUserDTO {
private String name;
private String description;
//other fields you want the clients to change.
...
}
现在,这个UpdateUserDTO可以像这样在更新方法中用作数据传输对象
public class UserController {
@RequestMapping(path="",method=RequestMethod.PUT)
public void update(@RequestBody UpdateUserDTO dto) {
//validate your dto properties and then update your user entity.
userService.save(user);
}
}
Session Session=sessionFactory.getCurrentSession();
字符串newuserId=newuser.getUserId();
session.clear();
User=userService.readUser(newuserId);
Property1-prop1=user.getProperty1();
List prop2=user.getProperty2();
session.clear();
newuser.setProp1(prop1);
newuser.setProp2(prop2);
newuser.save()//在保存aka之前,您应该检查服务和抽象层,它应该在DAO实现层中。
你的问题需要改进,但试试这个答案。
基本上,您可以将缺少的属性保存在一些变量中,并将它们附加到前端用户对象中。
基于HQL输出,似乎这样可以获取用户并向其添加其他属性
Session session = sessionFactory.getCurrentSession();
String newuserId=newuser.getUserId();
session.clear();
User user=userService.readUser(newuserId);
Property1 prop1=user.getProperty1();
List<Property2> prop2=user.getProperty2();
session.clear();
newuser.setProp1(prop1);
newuser.setProp2(prop2);
newuser.save(); //You should go through services and abstraction layers before saving aka it should be in the DAO implementation layer.