【发布时间】:2016-06-16 22:54:07
【问题描述】:
我有两个实体 Person 和 Visit
Person 与 Visit 具有 OneToMany 关系。
我想知道是否要保存一个新的访问条目,以及使用 RestController。我的方法正确吗?还是有其他更高效的方法?
所以我有以下控制器,它从 RequestBody 中获取 VisitModel,这样调用它是否正确?
VisitModel 具有人员 ID,以及访问实体所需的属性。我使用 person 的 ID 在 personRepository 中查找相关的 Person 条目,然后将其发布到一个新的 Visit 实例,然后使用 visitRepository 保存它。
@RequestMapping(value="", method=RequestMethod.POST)
public String checkIn(@RequestBody VisitModel visit) {
Person person = personRepository.findById(visit.personId);
Visit newVisit = new Visit(visit.getCheckIn, person);
visitRepository.save(newVisit);
return "success";
}
访问实体如下所示
@Entity
public class Visit {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@JsonProperty("check_in")
private Date checkIn;
@JsonProperty("check_out")
private Date checkOut;
@ManyToOne
@JoinColumn(name="personId")
private Person person;
public Visit(Date checkIn, Person person) {
this.checkIn = checkIn;
this.person = person;
}
public Date getCheckIn() {
return checkIn;
}
public void setCheckIn(Date checkIn) {
this.checkIn = checkIn;
}
public Date getCheckOut() {
return checkOut;
}
public void setCheckOut(Date checkOut) {
this.checkOut = checkOut;
}
public Person getPerson() {
return person;
}
}
我想知道下面的做法是否正确。还是有其他更好的方法?
【问题讨论】:
-
我可以看到的一个优化不是使用存储库方法获取人员对象,而是可以使用 new 运算符创建人员对象并填充 ID 字段并使用它。这将保存数据库命中以获取人员对象。
-
@MadhusudanaReddySunnapu 你的意思是关注
new Person(personId);? -
是的。你觉得这有什么问题吗?
标签: spring hibernate jpa spring-boot