我有一个简单的Java模型,名为Member with fields - ID(主键),Name(String),Position(String)
我想公开一个POST端点来更新成员的字段。这种方法可以接受像这样的有效载荷
{ "id":1,"name":"Prateek"}
或
{ "id":1,"position":"Head of HR"}
并根据收到的有效负载,我只更新该特定字段。如何使用JPARepository实现这一目标?
我的存储库界面是基本的 -
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository("memberRepository")
public interface MemberRepository extends JpaRepository<Member, Integer>{
}
我的会员模特 -
@Entity
@Table(name="members")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="member_id")
private Integer id;
@Column(name="member_name")
@NotNull
private String name;
@Column(name="member_joining_date")
@NotNull
private Date joiningDate = new Date();
@Enumerated(EnumType.STRING)
@Column(name="member_type",columnDefinition="varchar(255) default 'ORDINARY_MEMBER'")
private MemberType memberType = MemberType.ORDINARY_MEMBER;
public Member(Integer id, String name, Date joiningDate) {
super();
this.id = id;
this.name = name;
this.joiningDate = joiningDate;
this.memberType = MemberType.ORDINARY_MEMBER;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
public MemberType getMemberType() {
return memberType;
}
public void setMemberType(MemberType memberType) {
this.memberType = memberType;
}
public Member(String name) {
this.memberType = MemberType.ORDINARY_MEMBER;
this.joiningDate = new Date();
this.name = name;
}
public Member() {
}
}
答案 0 :(得分:2)
这样的事情可以解决问题
public class MemberService {
@Autowired
MemberRepository memberRepository;
public Member updateMember(Member memberFromRest) {
Member memberFromDb = memberRepository.findById(memberFromRest.getid());
//check if memberFromRest has name or position and update that to memberFromDb
memberRepository.save(memberFromDb);
}
}