![](/img/trans.png)
[英]How can I properly annotate this relationship between two entities using Hibernate & Spring Data JPA?
[英]How properly annotate hibernate entities
为我的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属性的不同,断言失败了,如图所示: 一种产品将其设置为null,另一种产品将其设置为{PersistentBag}。 当然,我可以通过编写自定义的equals方法(将忽略这些属性)来轻松破解它,但是请确保这不是最佳方法。
那么,为什么这些字段不同? 我确定正确注释实体字段的解决方案。
两个指针:
@LazyCollection(LazyCollectionOption.FALSE)
,因此当您检索实体时,ORM动态加载带有注释的字段,而在单元测试夹具中创建的实体是在ORM外部创建的,而您不会t重视这些领域。 @LazyCollection(LazyCollectionOption.FALSE)
,如果要对检索到的实体和由手创建的实体进行assertEquals( @LazyCollection(LazyCollectionOption.FALSE)
,也可能会有其他差异。 例如,对于Hibernate,您的惰性List
将不会为null
而是PersistentList
实例。 因此,您应该执行一些工作来执行断言。
您可以单独检查属性,也可以使用Reflection声明字段并忽略期望对象中空字段的比较。
检查http://www.unitils.org/tutorial-reflectionassert.html ,它可能会对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.