Spring数据JPA保存更新父实体

时间:2018-07-09 13:03:56

标签: java spring hibernate jpa spring-data-jpa

Student.java

@Entity
@Table(name = "Student")
@Data
@NoArgsConstructor
public class Student implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @OneToMany(mappedBy = "studentId", cascade = CascadeType.ALL)
   private List<Subject> subjectList = new ArrayList<>();

   public void addSubject(Subject subject) {
     subjectList.add(subject);
     subject.setStudentId(this);
   }

   @Column(name = "firstName")
   private String firstName;

   @Column(name = "lastName")
   private String lastName;

}

Subject.java

@Entity
@Table(name = "Subject")
@Data
@NoArgsConstructor
public class Subject implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name="studentId", nullable = false)
   private Student studentId;

   @Column(name = "subjectName")
   private String subjectName;

   @Column(name = "subjectCode")
   private int subjectCode;

}

SubjectRepository.java

@Repository
public interface SubjectRepository extends JpaRepository<Subject, Long> {


}

如上面的代码结构所示,我有2个实体(Student,Subject)和一个存储库类(SubjectRepository)。当我尝试保存到“主题”表中时,数据库中的“学生”表中的学生姓名“ Thomas”也会以某种方式更新。我只想插入Subject表,而没有更新Student表中的任何值。需要一些帮助。谢谢!

public static void main(String[] args) {

    @Autowired protected SubjectRepository subjectRepository;

    Student student = new Student();
    student.setFirstName("Thomas");

    Subject subject = new Subject();
    subject.setSubjectName("Chemistry");
    subject.setSubjectCode(12345);

    student.addSubject(subject)

    subjectRepository.save(subject)

}

2 个答案:

答案 0 :(得分:0)

  

我只想插入Subject表,而没有更新Student表中的任何值

您可以通过以下代码来实现:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="studentId", nullable = false, updatable = false)
private Student studentId;

答案 1 :(得分:0)

使用Spring JPA时,我建议使用JpaRepository API。您只需要传递您的实体,它就可以根据需要保存。

例如: subjectRepository.save(subject);