我有 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;
}
目前我的資料庫是這樣的:



關系:

物件的平等是通過比較他們的電子郵件來完成的
我有測驗這個案例的代碼:
@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));
};
}
}
我比較這些物件是錯誤的
結果是: 
我尋找除錯并看到,第一個實體在電子郵件中有哈希碼,另一個沒有第一個:

第二個:

uj5u.com熱心網友回復:
testClassRepository.findById(1L).get();回傳一個物件testChildCollection。當您生成一個新的時,TestClassChild您設定了 id 和電子郵件,但不是集合,但在您的示例中,Lombok 還使用testChildCollection來計算 equals/hashCode。
在使用繼承時,我通常盡量避免使用@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 生成的情況下做同樣的事情。
uj5u.com熱心網友回復:
問題是您的TestClassChild equals()方法還包括對其testChildCollection屬性的檢查。變數testClassChild具有非空的屬性,但testClass1將其設定為空。因此呼叫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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380107.html
