我在PUT請求中得到的響應有一些問題。所有更改都將保留並返回除以下兩個字段之外的所有數據:「created」:「null」,「lastUpdated」:「null」。我不明白爲什麼我在這裏得到一個空值。Spring,Creation和lastUpdate返回null
然而,在POST上,一切正常,正如所料,所有數據都包含在響應中,包括兩個有問題的字段:「created」:「2014-10-28T19:55:37.889Z」,「lastUpdated」:「 2014-10-28T19:55:37.889Z」
我的實體,看起來像這樣:
@Entity
@Table(name = "projects")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Project extends AbstractPersistable {
private String key;
private String name;
private String description;
@Column(name = "created_date", nullable = false, updatable = false)
@JsonSerialize(using = DateTimeSerializer.class)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime created;
@Column(name = "last_updated_date", nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@JsonSerialize(using = DateTimeSerializer.class)
private DateTime lastUpdated;
@PrePersist
public void onPersist() {
this.created = new DateTime();
this.lastUpdated = new DateTime();
}
@PreUpdate
public void onUpdate() {
this.lastUpdated = new DateTime();
}
//Getter and setter methods
這是我的資源類
@Path("/")
@Component
public class ProjectsResource {
@Autowired
private ProjectService projectService;
@POST
@Path("projects")
@Consumes(CustomMediaTypes.SMARTGWT_JSON)
@Produces(CustomMediaTypes.SMARTGWT_JSON)
public Response create(Project project) throws ServiceException {
projectService.createOrSave(project);
ProjectModelsSerializer jsonSerializer = new ProjectModelsSerializer();
jsonSerializer.visit(project);
return Response.status(Response.Status.CREATED).entity(jsonSerializer.asServiceResponse("success")).build();
}
@PUT
@Path("projects")
@Consumes(CustomMediaTypes.SMARTGWT_JSON)
@Produces(CustomMediaTypes.SMARTGWT_JSON)
public Object update(Project project) throws ServiceException {
projectService.createOrSave(project);
ProjectModelsSerializer jsonSerializer = new ProjectModelsSerializer();
jsonSerializer.visit(project);
return Response.status(Response.Status.CREATED).entity(jsonSerializer.asServiceResponse("success")).build();
}
謝謝你回到我身邊。我改變了@PUT: Project updated = projectService.createOrSave(project); ProjectModelsSerializer jsonSerializer = new ProjectModelsSerializer(); jsonSerializer.visit(更新); 它只返回「lastUpdated」,「創建」一個仍然爲空 – user2342259 2014-11-04 12:18:02
事實上,如果你使用合併,creationDate被合併結果覆蓋,在實體返回給你之前(用hibernate實現,你可以看看' org.hibernate.tuple.entity.AbstractEntityTuplizer#setPropertyValues')。你可以做的是(在你的createOrSave方法中):1)合併你的實體,2)flush()persitence上下文到數據庫,3)調用刷新(實體)來檢索創建日期。 – 2014-11-04 15:34:36
你可以看看http://stackoverflow.com/questions/3228304/jpa-merge-readonly-fields。另一個解決方案是使用手動合併來設置creationDate。 – 2014-11-05 08:49:46