Spring Boot Rest API为空Post属性

时间:2019-08-23 14:15:31

标签: java rest spring-boot post

我是Spring Boot的新手,我想编写我的第一个Rest API。

首先,我的模特:

package entity;

import base.BaseEntityAudit;
import lombok.Data;

import javax.persistence.*;
import java.util.List;

@Data
@Entity
public class Country extends BaseEntityAudit {

    @Column(nullable = false)
    private String countryName;

    @Column(nullable = false)
    private String alpha2Code;
@OneToMany(mappedBy = "country", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<League> leagues;

public Country(String countryName, String alpha2Code) {
    this.countryName = countryName;
    this.alpha2Code = alpha2Code;
}

public Country() {
}


}

此模型应与以下对象具有OneToMany关系:

    package entity;

import base.BaseEntityAudit;
import lombok.Data;

import javax.persistence.*;

@Data
@Entity
public class League extends BaseEntityAudit {

    private Long id;

    @Column(nullable = false)
    private String leagueName;

    @Column(nullable = false)
    private String leagueName_clean;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "country_id", referencedColumnName = "id")
    private Country country;

/*    @ManyToMany
    @Column(nullable = false)
    private Season season;*/
}

这个人有一个一对多协会。所以每个联赛都有一个国家

重要的是我认为联盟实体的控制者。有一个发布端点。如果我创建一个新的联赛,我想发送一个国家/地区ID以将联赛与一个国家/地区联系起来,但是我的问题是,尽管我在发帖请求中发送了“国家/地区”属性,但该属性始终为空。

    import org.springframework.web.bind.annotation.*;
import repository.CountryRepository;
import repository.LeagueRepository;
import response.StandardResponse;

import java.util.List;

@RestController
@RequestMapping(path = "/api/v1")
public class LeagueController {
    Logger logger = LoggerFactory.getLogger(LeagueController.class);

    private final LeagueRepository dataRepo;
    private final CountryRepository countryRepository;

    public LeagueController(@Autowired LeagueRepository datarepo, CountryRepository countryRepository) {
        this.dataRepo = datarepo;
        this.countryRepository = countryRepository;
    }

    @GetMapping(path = "/league", produces = MediaType.APPLICATION_JSON_VALUE)
    public StandardResponse getAllLeagues() {
        List<League> leagues = this.dataRepo.findAll();

        return new StandardResponse(HttpStatus.OK, leagues);
    }

    @PostMapping(path = "/league/add", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public StandardResponse createLeague(League l) {
        System.out.println(l);
        League league = this.dataRepo.save(l);

        return new StandardResponse(HttpStatus.OK, league);
    }
}

您可以看到Post Method的参数来自League类型。我不想更改参数。我缺少什么?谁能帮忙?

这是我发布的内容:

[{"key":"leagueName","value":"testLeague","description":"","type":"text","enabled":true},{"key":"country","value":"1","description":"","type":"text","enabled":true},{"key":"leagueName_clean","value":"testleague","description":"","type":"text","enabled":true}]

这是我的BaseEntityAudit。我使用它为每个实体自动更新了updateAt和createdAt字段:

    package base;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class BaseEntityAudit extends BaseEntity {
    @Column(name = "createdAt")
    @Temporal(TemporalType.TIMESTAMP)
private Date createdAt = new Date();

@Column(name = "updatedAt")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt = new Date();

public Date getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(Date createdAt) {
    this.createdAt = createdAt;
}

public Date getUpdatedAt() {
    return updatedAt;
}

public void setUpdatedAt(Date updatedAt) {
    this.updatedAt = updatedAt;
}

@PrePersist
public void setCreationDate() {
    this.createdAt = new Date();
}

/**
 * Sets updatedAt before update
 */
@PreUpdate
public void setChangeDate() {
    this.updatedAt = new Date();
}
}

enter image description here

2 个答案:

答案 0 :(得分:0)

在rest API中,如果要发布对象,则需要使用@RequestBody批注。因此,修改您的控制器

 @PostMapping(path = "/league/add" , consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public StandardResponse createLeague(League l) {
        System.out.println(l);
        League league = this.dataRepo.save(l);

        return new StandardResponse(HttpStatus.OK, league);
    }

 @PostMapping(path = "/league/add")
    public StandardResponse createLeague(@RequestBody League l) {
        System.out.println(l);
        League league = this.dataRepo.save(l);

        return new StandardResponse(HttpStatus.OK, league);
    }

现在在联赛课上评论本节。

  @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "country_id", referencedColumnName = "id")
    private Country country;

现在像这样的邮递员邮寄数据enter image description here

答案 1 :(得分:0)

我认为您的装饰标签不正确。我的RESTful API请求如下所示:

@RequestMapping(value = "/something", method = RequestMethod.POST)
    private @ResponseBody Antenna someMethod(@RequestBody Object o) {
        o.doSomthing();
    return o;
    }

看看 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap