Spring-Boot JPA - 在 JSON RequestBody 中使用外键插入 DB 会导致空对象 [英] Spring-Boot JPA - Inserting into DB with foreign keys in JSON RequestBody results in null object

查看:73
本文介绍了Spring-Boot JPA - 在 JSON RequestBody 中使用外键插入 DB 会导致空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Spring-Boot 和 Spring Data JPA 将记录保存到包含指向另一个表的外键的数据库表中.

I'm attempting to save records to a database table that includes a foreign key to another table using Spring-Boot and Spring Data JPA.

我的 JSON 如下所示:

My JSON looks like this:

{
    "requestId": 10080,
    "auditType": "C",
    "auditDate": "2019-06-12T17:25:43.511",
    "auditUsername": "cdunstal",
    "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eget porttitor velit. Fusce libero augue, tincidunt in vestibulum nec, lobortis tristique eros. Cras tempor est magna, eu dapibus metus bibendum non.",
    "isReportable": "Y"
}

我的实体如下所示:

@Entity
@Table(name = "CHANGE_AUDIT")
@SequenceGenerator(name = "CHANGE_AUDIT_PK_SEQ", sequenceName = "CHANGE_AUDIT_PK_SEQ", allocationSize = 1)
public class ChangeAudit {

    @Column(name = "AUDIT_ID")
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CHANGE_AUDIT_PK_SEQ")
    private Integer id;

    @Version
    private Long version;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "REQUEST_ID")
    @NotNull
    private ChangeRequest changeRequest;

    @Column(name = "AUDIT_TYPE", nullable = false, length = 1)
    @NotNull
    @Size(max = 1)
    private String auditType;

    @Column(name = "AUDIT_DATE", nullable = false)
    @NotNull
    private Date auditDate;

    @Column(name = "AUDIT_USER", nullable = false, length = 10)
    @NotNull
    @Size(max = 10)
    private String auditUsername;

    @Column(name = "AUDIT_MESSAGE", nullable = false, length = 4000)
    @NotNull
    @Size(max = 4000)
    private String message;

    @Column(name = "IS_REPORTABLE", nullable = false, length = 1)
    @NotNull
    @Size(max = 1)
    private String isReportable;

    // Constructor, getters and setters omitted.
}

我的控制器方法是:

@RequestMapping(value = "/changeAudit/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody()
public ChangeAudit createChangeAudit(@RequestBody ChangeAudit changeAudit) {
    logger.info("Creating new ChangeAudit: " + changeAudit.toString());
    return this.changeAuditService.createChangeAudit(changeAudit);
}

我收到以下错误:

{
    "timestamp": 1560412164364,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.transaction.TransactionSystemException",
    "message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction",
    "path": "/grade-admin-api/changeAudit/create"
}

由以下原因引起:

Caused by: javax.persistence.RollbackException: Error while committing the transaction
        at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:87)
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
        ... 78 common frames omitted
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [au.edu.csu.gradeadmin.api.entity.ChangeAudit] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
        ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=changeRequest, rootBeanClass=class au.edu.csu.gradeadmin.api.entity.ChangeAudit, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]

因此,在保存 ChangeAudit 时,它不会从 JSON 中获取 requestId 并将其转换为实体中的 ChangeRequest 对象.

So, when saving the ChangeAudit, it's not taking the requestId from the JSON and translating that to the ChangeRequest object in the Entity.

我似乎找不到可以解决我的问题的任何文档或教程或任何其他堆栈溢出问题.我尝试使用不同的类作为 @RequestBody 但它只是返回空值.我已经被困在这两天了,需要通过它,所以希望任何人都能提供任何帮助.

I can't seem to find any documentation or tutorial or any other stack overflow question that solves my problem. I have tried using a different class as the @RequestBody but it just comes back with null values. I've been stuck on this for two days and need to get passed it, so would appreciate any assistance anyone might be able to offer.

恕我直言,我不得不匆忙发布.如果您需要更多信息,请告诉我.

Forgive the brevity, I had to rush the posting. Please let me know if you need more info.

谢谢.

更新 - 答案

@user06062019 让我走上正轨.我更正了提交的 JSON 并将 CascadeType.ALL 添加到实体,但是,这给了我一个不同的错误 - 我无法将 null 插入 ChangeRequest.pidm.

@user06062019 put me on the right track. I corrected the submitted JSON and added the CascadeType.ALL to the Entity, however, this gave me a different error - that I couldn't insert null into ChangeRequest.pidm.

这是因为我在提交的 JSON 中将 requestId 作为外键,但是,它需要只是 id,这就是 ChangeRequest 类中的参数所调用的.然后我可以在 ChangeAuditService 中检索 ChangeRequest 类,将它添加到 ChangeAudit 对象并保存它.瞧!

This is because I had requestId as the foreign key in the submitted JSON, however, it needed to be just id, which is what the parameter in the ChangeRequest class is called. I could then retrieve the ChangeRequest class in the ChangeAuditService, add it to the ChangeAudit object and save it. Voila!

正确的 JSON:

{
    "changeRequest": {
        "id": 10080 
    },
    "auditType": "C",
    "auditDate": "2019-06-12T17:36:43.511",
    "auditUsername": "someuser",
    "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eget porttitor velit. Fusce libero augue, tincidunt in vestibulum nec, lobortis tristique eros. Cras tempor est magna, eu dapibus metus bibendum non.",
    "isReportable": "Y"
}

推荐答案

您发送给

createChangeAudit

ChangeAudit 对象需要 ChangeRequest 的对象类型,但请求 json 中缺少该对象类型.

The ChangeAudit object expects an object type for the ChangeRequest and that object type is missing in the request json.

因此,如果您将请求更改为这样的内容,则不应抱怨验证错误,其余部分将由 spring-data automagic 处理.

So if you change your request to something like this it should not complain about the validation error and rest will be taken care by the spring-data automagic .

{

    "auditType": "C",
    "auditDate": "2019-06-12T17:25:43.511",
    "auditUsername": "cdunstal",
    "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eget porttitor velit. Fusce libero augue, tincidunt in vestibulum nec, lobortis tristique eros. Cras tempor est magna, eu dapibus metus bibendum non.",
    "isReportable": "Y",
    "changeRequest":{
        "requestId": 10080
    }


}

你可能还需要提及 @ManyToOne 映射,cascade= CascadeType.ALL

Also you might need to mention on @ManyToOne mapping with cascade= CascadeType.ALL

这篇关于Spring-Boot JPA - 在 JSON RequestBody 中使用外键插入 DB 会导致空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆