我想玩一下hibernate、panache和quarkus。我想构建一个“跟踪”api,一个人可以有多个跟踪,但一个跟踪只能由一个人拥有。但我面临反序列化错误。
假设我想发布这个:
curl --location --request POST 'localhost:8080/trace' \
--header 'Content-Type: application/json' \
--data-raw '{
"traceOwner": "AtestOwner",
"participants": ["Karl", "John"],
"place": "10101, TestCity, TestStreet 25",
"startTime": "2016-07-20T23:07:41.907+02:00[Europe/Berlin]",
"stopTime": "2016-07-27T23:07:45.807+02:00",
"comment": "TestComment"
}'
我收到以下错误:
javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error: javax.json.bind.JsonbException:
Unable to deserialize property 'traceOwner' because of: Error deserialize JSON value into type: class
de.test.Person.
并在日志中:
2020-07-27 10:48:12,597 SEVERE [org.ecl.yas.int.Unmarshaller] (executor-thread-1) Unable to deserialize property 'traceOwner' because of: Error deserialize JSON value into type: class de.test.Person.
我的实体看起来像这样:
import java.time.ZonedDateTime;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
@Entity
public class Trace extends PanacheEntity {
@ManyToOne
public Person traceOwner;
@ElementCollection
public List<String> participants;
public String place;
@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE")
public ZonedDateTime startTime;
@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE")
public ZonedDateTime stopTime;
public String comment;
public String toString() {
return String.format("%s, [%s, %s], %s, %s, %s", this.traceOwner, this.participants.get(0),
this.participants.get(1), this.place, this.startTime, this.stopTime, this.comment);
}
}
和
import javax.persistence.Entity;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
@Entity
public class Person extends PanacheEntity {
public String name;
}
POST 端点如下所示:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrace(@Valid Trace trace) {
try {
LOG.info(trace);
transaction.begin();
trace.persist();
transaction.commit();
} catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException
| HeuristicMixedException | HeuristicRollbackException e1) {
LOG.error("Could not finish transaction to save entity", e1);
return Response.status(HttpStatus.SC_BAD_REQUEST).build();
}
return Response.ok(Trace.find("startTime =?1 AND traceOwner = ?2", trace.startTime, trace.traceOwner).firstResult())
.build();
}
为了避免缓存问题,我打开了一个新事务,但我想这不是问题吗?
我真的不明白为什么 jsonB 抱怨反序列化以及如何修复它。此外,在某些时候我想public List<String> participants
成为public List<Person> participants
但可以等到关系和反序列化工作。