Prateek Narendra
Prateek Narendra

Reputation: 1937

Spring JPARepository Update a field

I have a simple Model in Java called Member with fields - ID (Primary Key), Name (String), Position (String)

I want to expose an POST endpoint to update fields of a member. This method can accept payload like this

{ "id":1,"name":"Prateek"}

or

{ "id":1,"position":"Head of HR"}

and based on the payload received, I update only that particular field. How can I achieve that with JPARepository?

My repository interface is basic -

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository("memberRepository")
public interface MemberRepository extends JpaRepository<Member, Integer>{

}

My Member model -

@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() {

    }

}

Upvotes: 2

Views: 12144

Answers (1)

pvpkiran
pvpkiran

Reputation: 27078

Something like this should do the trick

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);
  }
}

Upvotes: 2

Related Questions