0
爲我的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屬性,你可以看到圖: 一個產品將其作爲null,另一個作爲{PersistentBag}。 當然,我可以通過編寫自定義equals方法(它將忽略這些屬性)輕鬆破解它,但確定它不是最好的方法。
那麼,爲什麼這些領域不同? 我確定在實體字段的正確註解中的解決方案。