如何正确注释休眠实体

问题描述:

为我的MVC webapp编写一些常用测试,并停止在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加载当你检索你的实体,而entites的在你的单元测试的夹具创建外部创建来自你的ORM,你不重视这些领域。
  • 即使你删除了@LazyCollection(LazyCollectionOption.FALSE),如果你想用一个检索到的实体和一个手工创建的实体来执行assertEquals(),你可能会有其他区别。例如,使用Hibernate,您的懒惰List将不会是null,而是PersistentList的实例。

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

查看http://www.unitils.org/tutorial-reflectionassert.html,它可能会帮助你。