我正在使用本教程使用 Netbean 7.3.1 创建简单的 Java EE 7 Web 服务。
它运行成功,我正在使用 GET、PUT、POST、DELETE 进行测试。除了 POST,这三个都工作正常。
我正在发布这个带有 ID 的 json 数据,效果很好。
{"id":"2","address1":"pe3","address2":"address line1","address3":"Address line3","city":"City Name","town":"Town Name","country":"uk","postcode":"123123"}
但是因为我的 ID 是自动递增的,所以当我在没有 id 的情况下发布以下 json 时,它会失败并出现以下错误
{"address1":"pe3","address2":"address line1","address3":"Address line3","city":"City Name","town":"Town Name","country":"uk","postcode":"123123"}
错误是
HTTP Status 400 - Bad Request
type Status report
messageBad Request
descriptionThe request sent by the client was syntactically incorrect.
GlassFish Server Open Source Edition 4.0
谁能解释为什么我需要在发送 POST 时发送数据库中自动递增类型的 ID?有什么解决办法吗?
实体类中的代码是
.......
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 45)
@Column(name = "address1")
private String address1;
@Size(max = 45)
@Column(name = "address2")
........
AddressFacadeREST.java 类看起来像这样。
package entities.service;
import entities.Address;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@Stateless
@Path("entities.address")
public class AddressFacadeREST extends AbstractFacade<Address> {
@PersistenceContext(unitName = "CustomerDBPU")
private EntityManager em;
public AddressFacadeREST() {
super(Address.class);
}
@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Address entity) {
super.create(entity);
}
@PUT
@Override
@Consumes({"application/xml", "application/json"})
public void edit(Address entity) {
super.edit(entity);
}
@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
super.remove(super.find(id));
}
@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Address find(@PathParam("id") Integer id) {
return super.find(id);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Address> findAll() {
return super.findAll();
}
@GET
@Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<Address> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
@Override
protected EntityManager getEntityManager() {
return em;
}
}