gpt4 book ai didi

java - 如何正确注释 hibernate 实体

转载 作者:行者123 更新时间:2023-12-01 09:29:46 25 4
gpt4 key购买 nike

为我的 MVC Web 应用程序编写一些常用测试,并在 findById() 测试处停止。我的模型类:

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

private String name;

private String description;

private double purchasePrice;

private double retailPrice;

private double quantity;

@ManyToOne
@JoinColumn (name = "supplier_id")
private Supplier supplier;

@ManyToOne
@JoinColumn (name = "category_id")
private Category category;

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

private String name;

private String description;

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<Product> products;

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

private String name;

@LazyCollection(LazyCollectionOption.FALSE)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@OneToOne
private Contact contact;

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany
private List<Product> products;

我的测试代码:

private Product productTest;
private Category categoryTest;
private Supplier supplierTest;

@Before
public void setUp() throws Exception {
categoryTest = new Category("Test category", "", null);
supplierTest = new Supplier("Test supplier", null, null);
productTest = new Product("Test product","", 10, 20, 5, supplierTest, categoryTest);

categoryService.save(categoryTest);
supplierService.save(supplierTest);
productService.save(productTest);
}

@Test
public void findById() throws Exception {
Product retrieved = productService.findById(productTest.getId());
assertEquals(productTest, retrieved);
}

好吧,断言失败了,因为product.category.products和product.supplier.products属性不同,如图所示: enter image description here一种产品将其设置为 null,另一种产品将其设置为 {PersistentBag}。当然,我可以通过编写自定义 equals 方法(它将忽略这些属性)轻松破解它,但可以肯定这不是最好的方法。

那么,为什么这些字段不同呢?我确信实体字段正确注释的解决方案。

最佳答案

两个指针:

  • 您在关系字段中使用 @LazyCollection(LazyCollectionOption.FALSE),因此当您在单元测试的固定装置中创建实体时,当您检索实体时,带有该注释的字段会由 ORM 动态加载是在您的 ORM 外部创建的,您不重视这些字段。
  • 即使您删除了@LazyCollection(LazyCollectionOption.FALSE),如果您想对检索到的实体和手动创建的实体执行assertEquals(),也可能会有其他差异。例如,使用 Hibernate,您的惰性 List 不会是 null,而是 PersistentList 的实例。

因此,您应该执行一些工作来执行断言。
您可以单独检查属性,也可以使用反射来断言字段并忽略预期对象中空字段的比较。

检查http://www.unitils.org/tutorial-reflectionassert.html ,也许对你有帮助。

关于java - 如何正确注释 hibernate 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com