![](/img/trans.png)
[英]Cache and use only one object in case of equality - equal objects should get referneces
[英]Why entity objects are not equal if I get one of that object with another fetched object that has collection elements although they should be?
我有 3 個相互關聯的實體類
測試類父:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = "email")
@Inheritance(strategy = InheritanceType.JOINED)
public class TestClassParent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
}
測試類孩子:
@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class TestClassChild extends TestClassParent{
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "test_collection_id")
private TestChildCollection testChildCollection;
}
測試子集合:
@Entity
@Data
@EqualsAndHashCode(of ="id")
@AllArgsConstructor
@NoArgsConstructor
public class TestChildCollection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "testChildCollection",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<TestClassChild> testClassChildSet;
}
目前我的數據庫如下所示:
關系:
通過比較它們的 email 來完成對象的相等性
我有測試這種情況的代碼:
@SpringBootApplication
@AllArgsConstructor
public class DemoApplication {
private final TestClassChildRepository testClassRepository;
private final TestChildCollectionRepository testChildCollectionRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public ApplicationRunner applicationRunner() {
return args -> {
TestClassChild testClassChild = testClassRepository.findById(1L).get();
TestClassChild testClass1 = new TestClassChild();
testClass1.setId(testClassChild.getId());
testClass1.setEmail(new String("newTestEmail2"));
System.out.println(testClass1.equals(testClassChild));
};
}
}
我因為比較這些對象而誤會了
我尋找調試並看到,第一個實例在 email 中有哈希碼,而另一個沒有第一個:
第二個:
testClassRepository.findById(1L).get();
返回帶有 testChildCollection 的testChildCollection
。 當您生成一個新的TestClassChild
時,您設置 id 和 email,但不是集合,但在您的示例中,Lombok 還使用testChildCollection
來計算 equals/hashCode。
使用 inheritance 時,我通常會盡量避免使用@Data
,因為很容易忘記實際生成 equals/hashCode 的方式。
@Entity
@Getter
@Setter
@ToString(callSuper = true) // Only if you really need a toString implementation that also prints your collection.
public class TestClassChild extends TestClassParent
將在沒有 hashCode/equals 生成的情況下做同樣的事情。
問題是您的TestClassChild
equals()
方法還包括對其testChildCollection
屬性的檢查。 變量testClassChild
的屬性不是 null,但testClass1
的屬性是 null。 因此調用testClass1.equals(testClassChild)
將始終為false
。
如果您只想依賴超類equals()
實現,則必須排除testClassChild
,如下所示:
@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class TestClassChild extends TestClassParent{
@EqualsAndHashCode.Exclude
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "test_collection_id")
private TestChildCollection testChildCollection;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.