我正在尝试创建一个对象Activity,它是与类(class)多对一关系的一部分(一门类(class)可以有多个 Activity )。
当我尝试保留新的 Activity 对象时,出现以下错误:
org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : app.model.activity.Activity.course -> app.model.Course
我将包含相关代码。
Controller POST方法
@RequestMapping(value = "/activities", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @ResponseBody ResponseEntity<Void> createActivity(@Valid @RequestBody ActivityPostDto activityPostDto, UriComponentsBuilder ucBuilder) {
CourseDto courseDto = courses.findById(activityPostDto.getCourseId());
Course course = modelMapper.map(courseDto, Course.class);
if (course==null){
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
ActivityType activityType = activityService.findType(activityPostDto.getTypeId());
if (activityType==null){
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
Activity activity = new Activity();
activity.setCourse(course);
activity.setType(activityType);
activity.setName(activityPostDto.getName());
activity.setDate(new Date(activityPostDto.getDate()));
activity = activityService.add(activity);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/activities/{id}").buildAndExpand(activity.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
ActivityPostDto 类
public class ActivityPostDto implements Item {
@NotNull
private Long date;
@NotNull
private String name;
@NotNull
private Long courseId;
@NotNull
private Long typeId;
...
}
Activity 类别
public class Activity implements Item, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@ManyToOne
@JoinColumn(name = "type_id", nullable = false)
private ActivityType type;
@ManyToOne
@JoinColumn(name = "course_id", nullable = false)
@JsonSerialize(using = CustomCourseSerializer.class)
private Course course;
...
}
类(class)类别
public class Course implements Item, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@OneToMany(mappedBy = "course", fetch = FetchType.EAGER, targetEntity = Activity.class, cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SUBSELECT)
@JsonSerialize(using = CustomActivityListSerializer.class)
private List<Activity> activities;
...
}
我已经阅读了一些有关此问题的内容,但找不到解决方案。任何帮助将非常感激。谢谢。
最佳答案
看起来,类(class)
不包含id
。
你可以这样做:
// it can be changed to check existence of id
CourseDto courseDto = courses.findById(activityPostDto.getCourseId());
if (courseDto ==null){
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
Course course = new Course();
course.setId(activityPostDto.getCourseId()) ;
Activity activity = new Activity();
activity.setCourse(course);
activity = activityService.add(activity);
关于java - 在Spring中创建多对一关系的对象(非空属性引用 transient 值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42745285/