开发者

JAXB+JPA+JAX-RS, JAXB Annotation problem

Hello and excuse my english!

Suppose I have this entity with this namedquery that select the name column with the jaxb annotations.

@Entity
@NamedQueries({
        @NamedQuery(name = "Person.selectAll", query = "SELECT p FROM Form p"),
        @NamedQuery(name = "Person.selectName", query = "SELECT p.id,p.name FROM Form p"),
});
@XmlRootElement
public class Person implements Serializable {

    @Id
    @Column
    private int id;

    @XmlElement
    private String name;

    @Column
    @XmlElement
    private String surname;
    ..
}

Suppose now i have a Rest method that executes the namedquery Person.selectName and returns XML or开发者_StackOverflow JSON code of the response.

@GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    @Path("/list")
    public List<Person> getList()
    {
        //here i execute the namedquery Person.selectName
        List<Person> persons = executeNamedQuery().getList();    
        return persons;
    }

Now the problem is during the marshalling because there's not a @XmlRootElement annotation for the name field. I would the output like <Persons><Person><name>value1</name></Person><Person><name>value2</name></Person> without the <surname> tags only when the namedquery Person.selectName is executed. And i can't use the @XmlTransient because the namedquery "selectAll" wants that one. How to solve in "elegant manner"?


You can use JAXB @XmlTransient annotation on the surname property without affecting how the JPA named query works.

@Column
@XmlTransient
private String surname;

UPDATE

You can solve this by creating a new class, PersonName. This class will only have the fields you want mapped with JAXB. This class will be returned by the getList() method, and in that method you will need to convert the List<Person> to List<PersonName>.

If you are using EclipseLink as your JPA provider then you can also do the following:

  • http://eclipselink.blogspot.com/2010/08/using-partial-eclipselink-jpa-entities.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜