Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring引导Rest API空Post属性_Java_Rest_Spring Boot_Post - Fatal编程技术网

Java Spring引导Rest API空Post属性

Java Spring引导Rest API空Post属性,java,rest,spring-boot,post,Java,Rest,Spring Boot,Post,我是SpringBoot新手,我想编写我的第一个RESTAPI 首先,我的模型: 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

我是SpringBoot新手,我想编写我的第一个RESTAPI

首先,我的模型:

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() {
}


}
这一个有一个单一的协会。所以每个联赛都有一个国家

我认为重要的是联盟实体的控制者。有一个Post端点。如果我创建了一个新的联盟,我想发送一个国家Id来将联盟与一个国家关联起来,但我的问题是,“国家”属性始终为空,尽管我在post请求中发送了它

    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);
    }
}
这是我的基本审计。我使用它为每个实体自动设置updatedAt和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();
}
}

在RESTAPI中,如果要发布对象,需要使用
@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);
    }

现在在联赛课上评论这一部分

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

现在,在邮递员发布的数据中,如下图所示,我认为您的装饰标签不正确。我的RESTful API请求如下所示:

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

是国家为空,还是整个联盟(l)对象为空?国家为空null@b0ss你查过我的答案了吗?对不起,我没有时间。现在我收到了这样一条消息:“JSON解析错误:无法构造
实体.Country
的实例(尽管至少存在一个创建者):没有int/int参数构造函数/工厂方法从数值(1)反序列化;嵌套异常为com.fasterxml.jackson.databind.exc.MismatchedInputException:无法构造
实体.Country
的实例(尽管至少存在一个创建者):在[Source:(PushbackInputStream);第4行,第13列]没有int/int参数构造函数/工厂方法从数值(1)反序列化(通过引用链:entity.League[\“country\”]),这给了我:“Content type'application/x-www-form-urlencoded;charset=UTF-8'不受支持”@b0ss您可以检查数据库是否保存了数据吗?@b0ss您可以尝试从
@PostMapping(path=“/League/add”)中删除所有参数吗
。请尝试在我编写时编写控制器。它不会保存,如果我删除了我获取的参数:“无法执行语句;SQL[n/a];约束[null];嵌套异常为org.hibernate.exception.ConstraintViolationException:无法执行语句”@b0ss您收到错误,因为您的某些实体值在发布期间可能为null。因此,请尝试删除“@Column(nullable=false)`此类型验证。或者确保所有具有验证的实体值均不为null。错误:“Content type”application/x-www-form-urlencoded;charset=UTF-8“不支持”
 @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;
@RequestMapping(value = "/something", method = RequestMethod.POST)
    private @ResponseBody Antenna someMethod(@RequestBody Object o) {
        o.doSomthing();
    return o;
    }