简体   繁体   English

Spring JPA联合表未返回所有字段

[英]Spring JPA joint table doesn't return all fields

I created two tables -student and subject. 我创建了两个表格-学生和主题。 Then I created a third table student_subject, which is a joint table to connect students with subjects. 然后,我创建了第三个表student_subject,这是一个将学生与科目联系起来的联合表。 It has 5 fileds: row id, student id, subject id and the created_at and updated_at fields (which comes from the AuditModel class): 它具有5个字段:行ID,学生ID,学科ID和created_at和Updated_at字段(来自AuditModel类):

  package com.rest.web.postgresapi.data.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

@Entity
@Table(uniqueConstraints = {
        @UniqueConstraint(columnNames = {"student_id", "subject_id"})
})
public class StudentSubject extends AuditModel {

    @Id
    @GeneratedValue(generator = "enrollment_generator")
    @SequenceGenerator(
            name = "enrollment_generator",
            sequenceName = "enrollment_sequence",
            initialValue = 4420
    )
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "student_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Student student_id;  // If I put private Long student_id, it fails

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "subject_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Subject subject_id; // If I put private Long subject_id, it fails

    // Constructors
    protected StudentSubject() {}

    public StudentSubject(Student student_id, Subject subject_id) {
        this.student_id = student_id;
        this.subject_id = subject_id;
    }

    // Getters
    public Long getId() {
        return id;
    }

    public Student getStudent_id() {
        return student_id;
    }

    public Subject getSubject_id() {
        return subject_id;
    }

    // Setters
    public void setId(Long id) {
        this.id = id;
    }

    public void setStudent_id(Student student) {
        this.student_id = student;
    }

    public void setSubject_id(Subject subject) {
        this.subject_id = subject;
    }

}

The application perfectly creates the tables in the database and I can get and post in the student and subject tables. 该应用程序完美地在数据库中创建了表,我可以在student和subject表中进行获取和发布。 No problem with that. 没问题。 The pain comes with the controller for the joint table. 疼痛来自关节台控制器。

This is the controller for the student_subject joint table table 这是student_subject联合表表的控制器

package com.rest.web.postgresapi.controllers;

import com.rest.web.postgresapi.data.models.StudentSubject;
import com.rest.web.postgresapi.repository.StudentSubjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

import java.util.List;

@RestController
public class StudentSubjectController {

    @Autowired
    private StudentSubjectRepository studentSubjectRepository;

    @GetMapping("/enrollments")
    public List<StudentSubject> getAllStudentsSubjects(){
        return studentSubjectRepository.findAll();
    }

    @PostMapping("/enrollments/student/subject")
    public StudentSubject createStudentSubject(@Valid @RequestBody StudentSubject studentSubject) {
        return studentSubjectRepository.save(studentSubject);
    }

}

There are two problems: 有两个问题:

1 .- when I do the get from the student_subject table, It only retrieves the id of the row and the created_at and updated_at fields. 1 .-当我从student_subject表中进行获取时,它仅检索行的id以及created_at和updated_at字段。 No student_id nor subject_id. 没有Student_id或subject_id。

response from get 得到回应

2 .- when I do the post (from postman) to insert a row, I got the following error: 2 .-当我(从邮递员)张贴帖子以插入一行时,出现以下错误:

Detail: Failing row contains (4671, 2018-11-20 11:04:34.176, 2018-11-20 11:04:34.176, null, null).

I provide both student_id and subject_id, as you can see at this screenshot from postman, but the error clearly states both fields are null: 正如您在邮递员的此屏幕快照中所见,我同时提供了student_id和subject_id,但错误明确指出两个字段均为空:

postman post 邮差

It seems that my definition of the table is somehow wrong. 我对表格的定义似乎是错误的。 What am I missing in my code? 我的代码中缺少什么?

Spring MVC uses Jackson to serialize/deserialize Java objects to/from JSON. Spring MVC使用Jackson将Java对象与JSON序列化/反序列化。

If you annotate an attribute with @JSONIgnore then Jackson will ignore it. 如果使用@JSONIgnore注释属性,那么Jackson将忽略它。

This is the reason why you don't see the student_id field or the subject_id field in your JSON response of the GET method. 这就是为什么在GET方法的JSON响应中看不到student_id字段或subject_id字段的原因。 Because Jackson is ignoring them when converts from object to json. 因为当从对象转换为json时,杰克逊会忽略它们。

And this is the reason why your POST fails. 这就是您的POST失败的原因。 Because Jackson is ignoring the received attributes. 因为Jackson忽略了接收到的属性。 Jackson is creating an empty entity and JPA is saving the entity without student_id and subject_id . 杰克逊(Jackson)正在创建一个空实体,而JPA(JPA)正在保存该实体,而没有student_idsubject_id

Solved by replacing 通过更换解决

@JsonIgnore @JsonIgnore

with

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) @JsonIgnoreProperties({“ hibernateLazyInitializer”,“ handler”})

as indicated in this answer 如本答案所示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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