【问题标题】:Spring Boot Rest API empty Post AttributeSpring Boot Rest API 空 Post 属性
【发布时间】:2019-12-28 21:14:47
【问题描述】:

我是 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;*/
}

这个有一个 OneToMany 关联。所以每个联赛都有一个国家

我认为重要的是联盟实体的控制器。有一个 Post Endpoint。如果我创建一个新联赛,我想发送一个国家 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。我用它来为每个实体自动更新At和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();
}
}

【问题讨论】:

  • 是国家为空,还是整个联盟(l)对象为空?
  • 国家为空
  • @b0ss 你检查我的答案了吗?
  • 抱歉没有时间。所以现在我得到了这个:
  • "message": "JSON 解析错误:无法构造 entity.Country 的实例(尽管至少存在一个 Creator):没有 int/Int-argument 构造函数/工厂方法可以从数值反序列化(1 ); 嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法构造 entity.Country 的实例(尽管至少存在一个 Creator):没有 int/Int-argument 构造函数/工厂方法可以从 Number 值反序列化 (1 )\n at [Source: (PushbackInputStream); line: 4, column: 13] (通过引用链: entity.League[\"country\"])",

标签: java rest spring-boot post


【解决方案1】:

在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;

现在像这张图片这样的邮递员帖子数据

【讨论】:

  • 这给了我:“不支持内容类型 'application/x-www-form-urlencoded;charset=UTF-8'”
  • @b0ss 你能检查数据库是否保存数据吗?
  • @b0ss 你能尝试从@PostMapping(path = "/league/add") 中删除所有参数吗?请尝试按照我写的方式编写控制器。
  • 它没有保存,如果我删除了我得到的参数:“无法执行语句;SQL [n/a];约束 [null];嵌套异常是 org.hibernate.exception.ConstraintViolationException:无法执行语句”
  • @b0ss 您收到错误,因为您的某些实体值在发布期间可能为空。所以请尝试删除 `@Column(nullable = false)` 这种类型验证。或者确保所有带有验证的实体值都不为空。
【解决方案2】:

我认为您的装饰器标签不正确。我的 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

【讨论】:

  • 错误:“内容类型 'application/x-www-form-urlencoded;charset=UTF-8' 不支持”
猜你喜欢
  • 2017-11-02
  • 2019-07-29
  • 2021-04-07
  • 1970-01-01
  • 2018-12-29
  • 2018-09-27
  • 2018-02-15
  • 1970-01-01
  • 2021-08-28
相关资源
最近更新 更多