【问题标题】:How to pass data into a foreign key , while passing data i am getting null using postman?如何将数据传递到外键,同时传递数据我使用邮递员得到空值?
【发布时间】:2020-01-10 09:38:52
【问题描述】:

我正在尝试以外键传递数据,但我得到的是空值。请参阅下面的代码:

这是特征 pojo 类:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "Feature", description = "This class is used to specify the Feature Property")
@Entity
public class Feature {
    @ApiModelProperty(notes = "unique feature id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long featureId;

    @NotNull
    @ApiModelProperty(notes = " feature name will define name of the feature")
    @Size(max = 50)
    private String name;
    @NotEmpty(message = "feature version should never be empty")
    @Size(max = 20)
    @ApiModelProperty(notes = "feature version will define version of the feature")
    @Column(unique = true)
    private String version;

    @NotBlank
    @Size(max = 500)
    @ApiModelProperty(notes = "feature description will describe the feature")
    private String description;

    @ManyToOne
    @JoinColumn(name = "plan_id")
    private Plan plan;
}

这就是计划

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "PlanData", description = "Plan is a pojo class under plan management")
@Entity
public class Plan {

    @ApiModelProperty(notes = "unique plan id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Plan_Id")
    private Long planId;

    @ApiModelProperty(notes = "A plan name")
    private String planName;


    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @DateTimeFormat
    @ApiModelProperty(notes = "plan start date will defines from what date the plan is active ")
    private Date planStartDate;


    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @DateTimeFormat
    @ApiModelProperty(notes = "plan end date will define till what date the plan will active ")
    private Date planEndDate;
    @ApiModelProperty(notes = "planDescription defines about the plan in detail")
    private String planDescription;
    @ApiModelProperty(notes = "plan version specifies version sepecific knowledge")
    private String planVersion;
    @ApiModelProperty(notes = "planStatus defines the active/deactive status of plan")
    @JsonProperty
    @Column(nullable = false, columnDefinition = "BOOLEAN")
    private Boolean planStatus = true;

    @OneToMany(mappedBy = "plan", cascade = CascadeType.ALL)
    private Set<Feature> features=new HashSet<Feature>();;

    @OneToOne
    @JoinColumn(name = "templateId")
    @ApiModelProperty(notes = "This property is mainly use to bind with the template")
    private Template template;

    @OneToOne
    @JoinColumn(name = "termsId")
    @ApiModelProperty(notes = "This property is mainly use to bind with the terms")
    private TermsAndConditions terms;

这是计划的发布 api

@PostMapping(value = "/plan")
    public ResponseEntity<PlanDTO> createPlan(@RequestBody PlanDTO planDTO ) {
        PlanDTO plan = planImpl.createPlan(planDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(plan);
    }

这是发布功能的 api

    @ApiOperation("This api will use to create a feature data ")
    @PostMapping(value = "/feature")
    public ResponseEntity<FeatureDTO> createFeature(@RequestBody FeatureDTO featureDTO) {
        FeatureDTO feature = featureImpl.createFeature(featureDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(feature);
    }

这个我通过邮递员请求发送:

{
    "planName": "bnvn",
    "planStartDate": "2003-09-09",
    "planEndDate": "2003-09-09",
    "planDescription": "hvxncbvnc jfbvfd nbhnsdf cbc",
    "planVersion": "cvnm mxcnvbnc xncv",
    "planStatus": true,
    "features": [{"planId":1
    }],
  "template": {
    "templateId" :1
   },
  "terms": {
    "termsId" :1
   }
}

我在所有外键字段中都得到了空值。

{
    "planId": 3,
    "planName": "bnvn",
    "planStartDate": "2003-09-09T00:00:00.000+0000",
    "planEndDate": "2003-09-09T00:00:00.000+0000",
    "planDescription": "hvxncbvnc jfbvfd nbhnsdf cbc",
    "planVersion": "cvnm mxcnvbnc xncv",
    "planStatus": true,
    "features": [],
    "template": null,
    "terms": null
}

这就是计划


@Data
public class PlanDTO {
    private Long planId;
    private String planName;
    private Date planStartDate;
    private Date planEndDate;
    private String planDescription;
    private String planVersion;
    private Boolean planStatus;
    private Set<Feature> features = new HashSet<Feature>();
    private Template template;
    private TermsAndConditions terms;

    public PlanDTO() {
    }

    public PlanDTO(Long planId, String planName, Date planStartDate, Date planEndDate, String planDescription,
            String planVersion, Boolean planStatus, Set<Feature> features, Template template,
            TermsAndConditions terms) {
        super();
        this.planId = planId;
        this.planName = planName;
        this.planStartDate = planStartDate;
        this.planEndDate = planEndDate;
        this.planDescription = planDescription;
        this.planVersion = planVersion;
        this.planStatus = planStatus;
        this.features = features;
        this.template = template;
        this.terms = terms;
    }
}

这是 dto 的功能:

@Data
public class FeatureDTO {
    private Long featureId;
    private String name;
    private String version;
    private String Description;
    private Plan plan;

    public FeatureDTO() {
    }

    public FeatureDTO(Long featureId, String name, String version, String description, Plan plan) {
        super();
        this.featureId = featureId;
        this.name = name;
        this.version = version;
        this.Description = description;
        this.plan = plan;
    }

}

这是计划实现类

@Service
public class PlanImpl {

    private static final Logger logger = LoggerFactory.getLogger(PlanImpl.class);

    @Autowired
    private PlanRepo planRepo;

    @Autowired
    private PlanMapper planMapper;

    /**
     * createPlan will create a plan and will store it in repository
     * 
     * @param plan
     * @return
     */
    public PlanDTO createPlan(PlanDTO planDTO) {
        Plan plan = planMapper.toPlan(planDTO);
        Plan planData = planRepo.save(plan);
        PlanDTO plans = planMapper.toPlanDTO(planData);
        return plans;

    }

    /**
     * update plan will update a plan using plan id and store it in database
     * 
     * @param planId
     * @param plan
     */
    public PlanDTO updatePlan(Long planId, PlanDTO planDTO) {
        Plan plan = planMapper.toPlan(planDTO);
        Plan updatePlan;

        if (planRepo.findById(planId) == null) {
            throw new NullPointerException();

        } else {
            plan.setPlanId(planId);

            updatePlan = planRepo.getOne(plan.getPlanId());
            updatePlan.setPlanName(plan.getPlanName());
            updatePlan.setPlanStartDate(plan.getPlanStartDate());
            updatePlan.setPlanEndDate(plan.getPlanEndDate());
            updatePlan.setPlanDescription(plan.getPlanDescription());
            updatePlan.setPlanVersion(plan.getPlanVersion());
            updatePlan.setPlanStatus(plan.getPlanStatus());

            Plan planUpdateData = planRepo.save(updatePlan);
            PlanDTO Plans = planMapper.toPlanDTO(planUpdateData);
            return Plans;
        }
}

我想展示一个具有多种功能的计划,但它返回 null。 谢谢!

【问题讨论】:

  • 你还没有发布DOT的代码。而且你还没有发布planImpl.updatePlan() 的代码。所以我们帮不上忙。
  • @JBNizet 我已经添加了 planImpl 类,谢谢您的回复。
  • 在您的 JSON 中,您有(例如)"features": [{"planId":1 }]。此 JSON 映射到 PlanDTO。 PlanDTO 确实有一个名为features 的属性。这是一个集合。但是Feature 中没有planId 属性。所以杰克逊对"planId":1 无能为力:它可能在哪里存储这些信息?不要在 DTO 中使用实体。根据您真正应该收到的内容设计用作服务参数的 DTO。
  • 请检查您的数据库中是否有计划和功能、模板等之间的映射数据。
  • @gnanajeyam95 映射列可用,但值为空。

标签: java spring-boot orm mapping one-to-many


【解决方案1】:

您需要将功能和模板添加到计划中。像这样的:

public class Plan {

   ...

   public void addFeature(Feature feature) {
       this.features.add(feature);
       feature.setPlan(this);
   }

   public void setTemplate(Template template) {
       this.template = template;
       template.setPlan(this);
   }
}

添加后,只需在保存计划之前调用 addFeature 和模板设置器即可。您甚至可以调整它以一次保存所有功能。

这里是关于如何使用 @OneToMany 和 @ManyToMany 进行映射的一个很好的来源 https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

【讨论】:

  • 这里是一个关于这个```方法的问题 setPlan(Plan) is undefined for the type Set```
猜你喜欢
  • 2020-06-09
  • 2021-09-14
  • 2011-05-14
  • 2012-08-03
  • 1970-01-01
  • 2017-06-10
  • 2017-03-25
  • 2023-02-06
  • 2021-12-17
相关资源
最近更新 更多