xml没有映射到java pojo

时间:2016-05-11 07:09:54

标签: java xml spring-rest

我正在尝试将xml发布到具有以下类的spring rest控制器。 XML正在为Team对象正确映射,但它不在Player对象中映射playerName。 playerName始终为null。谁能告诉我这里有什么问题。

我的播放器XML POJO

@XmlRootElement
@Entity(name = "player")
public class Player {

    @Id
    @GeneratedValue
    @Column(name = "player_id")
    private long player_id;

    @Column(unique=true , nullable = false)
    private String playerName;

    @ManyToOne
    @JoinColumn(name = "team_id")
    private Team team;

    public long getPlayer_id() {
        return player_id;
    }

    public void setPlayer_id(long player_id) {
        this.player_id = player_id;
    }


    public String getPlayerName() {
        return playerName;
    }

    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }

    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }


}

我的团队XML POJO

@XmlRootElement
@Entity(name = "team")
public class Team {

    @Id
    @GeneratedValue
    @Column(name = "team_id")
    private long team_id;

    @Column(unique=true , nullable = false)
    private String name;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "team")
    private List<Player> players;

    public long getTeam_id() {
        return team_id;
    }

    public void setTeam_id(long team_id) {
        this.team_id = team_id;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Player> getPlayers() {
        return players;
    }

    public void setPlayers(List<Player> players) {
        this.players = players;
    }


}

我的Spring Rest Controller方法

@RequestMapping(value="/team/", method = RequestMethod.POST , headers="Accept=application/xml")
    @ResponseStatus(value = HttpStatus.OK)
    public void createTeam(@RequestBody Team team) throws Exception {
        for (Player player: team.getPlayers()){
            player.setTeam(team);
        }
        teamService.createTeam(team);
    }

我发布给控制器的我的XML。

<team>
<name>GUj</name>
<players>
    <Player>
    <playerName>Raina</playerName> 
    </Player>
</players>
</team>

当我用播放器xml直接调用播放器休息方法然后它的工作。下面是创建播放器和播放器xml的其余代码。它看起来只有映射问题是父xml pojo中的子xml pojo。

@RequestMapping(value="/player/", method = RequestMethod.POST , headers="Accept=application/xml")
    @ResponseStatus(value = HttpStatus.OK)
    public void createPlayer(@RequestBody Player player) throws Exception {
        playerService.createPlayer(player);
    }

播放器xml

<player>
<playerName>Yuvraj</playerName> 
</player>

附加调试屏幕截图,其中我可以看到playerName为空

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要在“玩家”列表中定义XmlElement

@XmlElement(name="players")
public List<Player> getPlayers() {
    return players;
}

希望这有帮助!