0

我想通过 POST 请求将序列化对象发送到服务器。

        Paint paint = new Paint();
        paint.setYear(2010);
        paint.setTitle("title");


        JAXBContext jc = JAXBContext.newInstance(Paint.class, Art.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        java.io.StringWriter sw = new StringWriter();
        marshaller.marshal(paint, sw);

        ClientRequest request = new ClientRequest("http://localhost:8080/rest/createArt");

        request.body("application/xml", sw.toString());

        ClientResponse<Response> response = request.post(Response.class);

对于这个简单的服务:

@POST
@Path("/createArt")
@Consumes("application/xml")
public Response createArt(Art a){
    artDAO.createArt(a);
    return Response.ok(a).build();
}

但我收到以下错误:

DefaultClientConnection:249 - Receiving response: HTTP/1.1 400 javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"paint"). Expected elements are <{}art>, <{}photo>

为什么要开设这些课程?

Art.java:抽象类

@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@XmlRootElement(name = "art")
public abstract class Art {

@Id @GeneratedValue(strategy = GenerationType.AUTO) 
private int id;

@OneToMany (mappedBy="art",cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Photo> photo;
...
}

Paint.java :继承自 Art

@Entity
@XmlRootElement(name = "paint")
public class Paint extends Art{
@Enumerated(EnumType.STRING)
private SupportArt support;
@Enumerated(EnumType.STRING) 
private Realisation realisation;
...
}

照片.java

@Entity
@XmlRootElement(name = "photo")
public class Photo {

@Id @GeneratedValue(strategy = GenerationType.AUTO) 
private int id;

@ManyToOne 
@JoinColumn (name="art_id")
private Art art;

private String path;
...
}

我不明白我的错误,我认为这是 JAXB 注释的问题。继承也给我带来了一些麻烦。照片和艺术之间存在双向关系,当我删除它时,照片不再在预期的元素中(它持续 <{}art>)。

我在网上搜索并尝试了很多东西,但它并没有解决我的问题。

4

1 回答 1

1

我发现了我的错误,我只需要使用 XmlSeeAlso :

Art.java:抽象类

@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@XmlSeeAlso(Paint.class)
public abstract class Art {

也不得不修改这一行:

ClientResponse<String> response = request.post(String.class);
于 2012-12-25T17:24:37.903 回答