【发布时间】:2022-01-15 18:37:36
【问题描述】:
我有 3 个相互关联的实体类
TestClassParent:
@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;
}
TestClassChild:
@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class TestClassChild extends TestClassParent{
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "test_collection_id")
private TestChildCollection 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));
};
}
}
比较这些对象我会弄错
我寻找调试并看到,第一个实例在电子邮件中有哈希码,而另一个没有 第一个:
第二个:
【问题讨论】:
-
TestClassChild类中的字段testChildCollection用于equals() 方法,看来您需要@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)而不是@EqualsAndHashCode(callSuper = true)。顺便说一句,我确实认为以这种方式覆盖 equals/hashCode 方法不是一个好主意,请考虑以下内容:从技术上讲,JPA 记录表示 DB 行,相等的记录是否必须指向同一行?
标签: java hibernate set equals hashcode