利用springboot的jpa的API实现修改功能的一个小问题

 

问题背景

 在springboot中利用Spring DataJPA 的API实现修改功能时,按照书里讲的直接用set方法修改持久化对象的值即可,但我尝试了很多遍不行,经过摸索很快解决了这个小问题。

框架及版本

 1、 spring-boot-starter-parent   2.0.6.RELEASE

 2、 spring-boot-starter-data-jpa  2.0.1.RELEASE

 

主要代码如下


import javax.persistence.*;
import java.io.Serializable;

/*
  要操作的实体类
*/
@Entity
@Table(name = "tb_member")
public class Member implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private char sex;
    private int age;

    @ManyToOne(
            fetch = FetchType.LAZY,
            targetEntity = Party.class,
            cascade = CascadeType.ALL
    )
    @JoinColumn(name = "partyId",referencedColumnName = "code")
    private Party party;

    @Override
    public String toString() {
        return "Member{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }

    public Member(){}
    public Member(String name, char sex, int age,Party party) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.party = party;
    }

    public Party getParty() {
        return party;
    }

    public void setParty(Party party) {
        this.party = party;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

import com.enchi.youcanvote.youcanvotecore.Entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;

/*
  数据操作层
*/
public interface MemberRepository extends JpaRepository {

}

 

/*
  测试类代码  

*/ 
@Test
    @Transactional
    public void MemberTest() {
        Optional op = memberRepository.findById(1);
        Member member = op.get();
        member.setName("随便是谁");//按照书里讲的,获得持久化对象都直接set即可修改。事实上并不能
        memberRepository.saveAndFlush(member); //加上这句话就可以修改,注意,只用save是不行的
    }

参考书籍  《Spring Boot2企业应用实战》--疯狂软件 

 

你可能感兴趣的:(利用springboot的jpa的API实现修改功能的一个小问题)