我正在使用 Spring 框架开发一个基于 REST 的 JAVA 项目。我的一些 JPA 实体具有来自 jackson 的 @JsonIgnore
属性注释。下面的例子。
@Entity
@Table(name="TRANSACTION")
public class Transaction {
@Id
@Column(name="SERIAL", length=16)
private String serial;
@Column(name="NARRATION", length=128)
private String narration;
@OneToMany(mappedBy="transaction", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private List<TransactionDetail> details;
// other fields goes here
}
@Entity
@Table(name="TRANSACTION_DETAIL")
public class TransactionDetail {
@Id
@Column(name="UUID", updatable=false)
private String uuid;
@JsonIgnore
@ManyToOne
@JoinColumn(name="FK_TRANSACTION")
private Transaction transaction;
@Column(name="ACCOUNT_NO")
private int accountNo;
// other fields goes here
}
根据上述类关系,我希望仅在获取 Transactions
时应用 @JsonIgnore
。
List<Transactions> transactions = transactionsRepo.findAll()
但是如果我直接获取 TransactionDetails,我还需要获取 TransactionDetail
中的属性 transaction
。
List<TransactionDetail> details = transactionDetailsRepo.findByAccountNo(accountNo);
如何使用@JsonIgnore
来执行此操作?或者还有其他正确的方法来实现这一目标吗?
最佳答案
@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
@Table(name="TRANSACTION_DETAIL")
public class TransactionDetail {
@Id
@Column(name="UUID", updatable=false)
private String uuid;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="FK_TRANSACTION")
private Transaction transaction;
@Column(name="ACCOUNT_NO")
private int accountNo;
// other fields goes here
}
您可以尝试使用 fetchtype 作为lazy,它的作用是获取事务详细信息实体中的属性。但它不会获取 transaction_detail 的相关数据,这意味着所有其他数据将为空。您可以使用 @JsonInclude 注释您的实体,就像我所做的那样,仅包含非空值。 并请添加 jackson-datatype-hibernate Jar 文件,或者如果您使用 maven,请在 pom 文件中添加依赖项
关于java - 如何使用@JsonIgnore仅在对象不是根对象时应用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556249/