Spring Boot 如何阻止Hibernate攻击子表?

eagi6jfj  于 2023-10-16  发布在  Spring
关注(0)|答案(2)|浏览(109)

从图像中可以明显看出,Apple Block、Banana Block、Cat Block和Dog Block中的各个块都有一个指向Block Reference Table的外键引用,而Intern则引用了返回到Block Definition Table的Effective Date Table。
这是我的代码

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Block_Reference_Table", schema = "mySchema", catalog = "myCatelog")
public class BlockReference extends AuditableEntity<Long> implements java.io.Serializable {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Id
  @Column(name = "block_ref_table_id", nullable = false)
  private Long blockReferenceTableId;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "ref_to_effective_date_table")
  private EffectiveDateTable effectiveDate;

  @OneToOne(mappedBy = "BlockReference", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private AppleBlock appleBlock;

  @OneToOne(mappedBy = "BlockReference", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private BananaBlock bananaBlock;

  @OneToOne(mappedBy = "BlockReference", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private CatBlock catBlock; 

  @OneToOne(mappedBy = "BlockReference", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private DogBlock dogBlock;

我正在尝试根据生效日期检索单个块。我面临的问题是Hibernate正在攻击所有其他块(子表)。我该如何避免这种情况?
我想要的是,如果我试图检索基于有效日期的苹果块,引擎不应该打香蕉块,猫块或狗块.当我试图根据生效日期检索香蕉块时,engibe不应该击中苹果块,猫块或狗块。
如此这般,第四。

72qzrwbm

72qzrwbm1#

添加@JsonIgnoreProperties以指定在子json中忽略哪些值
下面是示例实现:
A类:

@Entity
public class EntityA {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToOne(mappedBy = "entityA")
    @JsonIgnoreProperties("entityA") // Ignore entityA in entityB
    private EntityB entityB;
}

B类:

@Entity
public class EntityB {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String info;

    @OneToOne
    @JoinColumn(name = "entity_a_id")
    @JsonIgnoreProperties("entityB") // Ignore entityB in entityA
    private EntityA entityA;
}
ckx4rj1h

ckx4rj1h2#

通过点击,我假设你是说你试图检索数据,而JPA生成的查询返回了一个带有不需要的子实体的大结果集,这将影响性能,这是我在你的实体定义中观察到的,你已经做了一个很好的工作,使一对一关系的获取类型为懒惰,但请注意,即使你改变了默认的获取,父端关联的行为将像FetchType.EAGER.因此,当您获取BLOCK图元时,关联的子图元也会随其一起加载沿着。
长话短说,我们可以通过在父端使用@LazyToOne(LazyToOneOption.NO_PROXY)来解决这个问题。

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "Block_Reference_Table", schema 
= "mySchema", catalog = "myCatelog")
public class BlockReference extends 
AuditableEntity<Long> implements 
java.io.Serializable {
@GeneratedValue(strategy = 
GenerationType.IDENTITY)
@Id
@Column(name = "block_ref_table_id", nullable 
= false)
private Long blockReferenceTableId;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = " 
ref_to_effective_date_table")
private EffectiveDateTable effectiveDate;

@LazyToOne(LazyToOneOption.NO_PROXY)
private AppleBlock appleBlock;

相关问题