【问题标题】:Foreign key not showing in GET request spring bootGET请求春季启动中未显示外键
【发布时间】:2020-05-01 12:43:04
【问题描述】:

我正在执行 GET 请求“/api/admin/tickets”。我没有得到 userId 作为回应。我已经检查了数据库并且 userId 存在那里。在实体“Ticket”中,userId 应充当外键。我不知道为什么我无法看到外键作为响应。我正在尝试在 User 和 Ticket 之间建立一对多的关系。

TicketController.java

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = Constants.ORIGIN)
public class TicketController {

    @Autowired
    private TicketRepository ticketRepository;

    @GetMapping("/admin/tickets")
    public Page<Ticket> getAllTickets(Pageable pageable) throws ResourceNotFoundException{
        return ticketRepository.findAll(pageable);
    }
}

User.java

@Entity
public class User extends AuditModel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;


    @Column(nullable = false)
    private String businessUnit;

    @Column(nullable = false)
    private String title;

    public User() {
    }

    // constructor with fields
    // getters and setters

}

Ticket.java

@Entity
public class Ticket extends AuditModel {
    @Id
    @Column(name = "ticketId")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "userId", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private User user;

    public Ticket() {
        super();
    }

    public Ticket(int id) {
        super();
        this.id = id;
    }

    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

TicketRepository.java

@Repository
public interface TicketRepository extends JpaRepository<Ticket, Integer>{

    Page<Ticket> findByUserId(Integer userId, Pageable pageable);
    Optional<Ticket> findByIdAndUserId(Integer ticketId, Integer userId);

}

【问题讨论】:

  • 首先有 @JsonIgnore 注释,表示从响应中排除。第二个用户被定义为惰性关联。

标签: java spring spring-boot jpa


【解决方案1】:

您在Ticket 类中使用@JsonIgnore 注释了User 字段,这可以防止在GET 响应中包含User 数据形式。

第二个问题可能是您使用FetchType.LAZY 延迟加载User 字段。这也可能会阻止数据包含在 GET 响应中。

【讨论】:

  • Lazy 不会,但@JsonIgnore 肯定会。
猜你喜欢
  • 1970-01-01
  • 2014-12-28
  • 2019-07-26
  • 2019-12-14
  • 1970-01-01
  • 2012-08-31
  • 2015-01-08
  • 2020-01-11
  • 1970-01-01
相关资源
最近更新 更多