我有一个实体与Composote关键对以下表:1-用户2-部门
我使用Spring Data通过JpaRepository的save方法保存实体,现在如果我在同一个transaction中保存后更新实体,更新不会发生,这是通过在同一个@ transaction中使用setter方法更新字段来完成的。
这似乎是我保存的实体(新实体)是不管理.这是因为实体主键不是长/短?
**更新:**如果我使用从保存返回的实体它工作,我认为因为主键不是null,Spring会认为它是合并而不是持久化,因此用于保存的实体与返回的实体不一样。
@Entity
@Table(name = "user")
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
}
@Entity
@Table(name = "department")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Entity
@Table(name = "COURSE")
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class Course {
@EmbeddedId private CourseId courseId;
private String name;
}
@Embeddable
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class CourseId implements Serializable {
@ManyToOne
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne
@JoinColumn(name = "DEPARTMENT_ID")
private Department department;
}
public interface CourseRepository extends JpaRepository<Course, CourseId> {
}
@Transactional
public void createCourse(){
User user=userRepository.findOneByName("user1");
Department department=departmentRepository.findOneByName("department");
CourseId courseId=new CourseId(user,department);
Course course=new Course();
course.setCourseId(courseId);
courseRepository.save(course);// here it works
course.setName("test"); // this doesn't update
}
字符串
1条答案
按热度按时间7d7tgy0s1#
它不工作的原因是主键不是null,因此Spring将实体视为merge而不是persistent。在merge中返回一个新的托管实体,因此我需要使用从保存返回的实体:
字符串