从输入流投递向导示例读取实体时出错



我正在尝试使用这个dropwizard示例并在此基础上构建。我尝试在 Person 中向people表添加一个列userName.java如下所示

public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "fullName", nullable = false)
private String fullName;
@Column(name = "jobTitle", nullable = false)
private String jobTitle;
@Column(name = "userName", nullable = false)
private String userName;
public Person() {
}
public Person(String fullName, String jobTitle, String userName) {
this.fullName = fullName;
this.jobTitle = jobTitle;
this.userName = userName;
}

我添加了适当的getter和setter,以及等于方法。

但是,我在此块中从输入流读取实体时出错。

@Test
public void testPostPerson() throws Exception {
final Person person = new Person("Dr. IntegrationTest", "Chief Wizard", "Dr. Wizard");
final Person newPerson = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/people")
.request()
.post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE))
-->    .readEntity(Person.class);
assertThat(newPerson.getId()).isNotNull();
assertThat(newPerson.getFullName()).isEqualTo(person.getFullName());
assertThat(newPerson.getJobTitle()).isEqualTo(person.getJobTitle());
assertThat(newPerson.getUserName()).isEqualTo(person.getUserName());
}

输入流错误由以下原因引起

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "code" (class com.example.helloworld.core.Person), not marked as ignorable (4 known properties: "fullName", "id", "userName", "jobTitle"])

类级别的@JsonIgnoreProperties注解能解决这个问题吗?这是安全的做法吗?

编辑:PersonResource.java

@Path("/people/{personId}")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
private final PersonDAO peopleDAO;
public PersonResource(PersonDAO peopleDAO) {
this.peopleDAO = peopleDAO;
}
@GET
@UnitOfWork
public Person getPerson(@PathParam("personId") LongParam personId) {
return findSafely(personId.get());
}
@GET
@Path("/view_freemarker")
@UnitOfWork
@Produces(MediaType.TEXT_HTML)
public PersonView getPersonViewFreemarker(@PathParam("personId") LongParam personId) {
return new PersonView(PersonView.Template.FREEMARKER, findSafely(personId.get()));
}
@GET
@Path("/view_mustache")
@UnitOfWork
@Produces(MediaType.TEXT_HTML)
public PersonView getPersonViewMustache(@PathParam("personId") LongParam personId) {
return new PersonView(PersonView.Template.MUSTACHE, findSafely(personId.get()));
}
private Person findSafely(long personId) {
return peopleDAO.findById(personId).orElseThrow(() -> new NotFoundException("No such user."));
}

我认为这是因为资源失败并抛出 Web 应用程序异常,代码实际上是 http 状态代码。

像这样尝试:

Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/people")
.request()
.post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));
assertEquals(200, response.getStatus());
Person newPerson = response.readEntity(Person.class);
....

您也可以像这样调试:

String responseString = response.readEntity(String.class);

这将倾倒你响应的正文。

最新更新