利用springboot的jpa的API實現修改功能的一個小問題
阿新 • • 發佈:2019-01-25
問題背景
在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<Member,Integer> {
}
/* 測試類程式碼 */ @Test @Transactional public void MemberTest() { Optional<Member> op = memberRepository.findById(1); Member member = op.get(); member.setName("隨便是誰");//按照書裡講的,獲得持久化物件都直接set即可修改。事實上並不能 memberRepository.saveAndFlush(member); //加上這句話就可以修改,注意,只用save是不行的 }
參考書籍 《Spring Boot2企業應用實戰》--瘋狂軟體