【发布时间】: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