简体   繁体   中英

Spring Boot Rest API empty Post Attribute

Im new to spring boot and I want to code my first Rest API.

First of all my Models:

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


}

This Model should have a OneToMany relation to the following:

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

This one has a OneToMany Association. So each League has a country

The important thing is the controller for league Entity I would think. There is a Post Endpoint. If I create a new League, I want to send a country Id with it to associate the League with a country, but my Problem is, that the "country" attribute is always null allthough I send it in my post request.

    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);
    }
}

You can see the parameter of the Post Method is from type League. I don't want to change the parameter. What Im missing? Can anyone Help?

This is what Im Posting:

[{"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}]

This is my BaseEntityAudit. Im using it to have updatedAt and createdAt fields automaticcly for each entity:

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

在此处输入图片说明

In rest API if you want to post object you need to use @RequestBody annotation. So modify your controller

 @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);
    }

to

 @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);
    }

Now comment this section at league class.

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

Now in postman post data like this image在此处输入图片说明

I think your decorator tags are incorrect. My RESTful API requests look like this :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM