Hi.
I have a situation in which my JUnit test have a some strange behaviour. Help me to understand what is going on here. I have a OneToMany relation between Stock and Item.
Code:
@Entity
@Table(name = "STCK")
public class Stock implements Serializable {
@Id
@SequenceGenerator(name = "STCK_GEN", sequenceName = "STCK_SEQ", allocationSize = 5)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STCK_GEN")
@Column(name = "STCK_ID")
private int id;
@OneToMany(mappedBy = "stock", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Item> items = Sets.newLinkedHashSet();
}
@Entity
@Table(name = "ITMS")
public class Item implements Serializable {
@Id
@SequenceGenerator(name = "ITMS_GEN", sequenceName = "ITMS_SEQ", allocationSize = 20)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ITMS_GEN")
@Column(name = "ITMS_ID")
private int id;
@ManyToOne
@JoinColumn(name = "STCK_ID")
private Stock stock;
}
Nothing unusual here. Then my unit test that checks cascade save operation.
Code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-dao.xml"})
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public class ItemDaoIT {
@Autowired
private ItemDao itemDao;
@Autowired
private StockDao stockDao;
@Test
public void testCascade(){
Stock newStock = new Stock();
Long stockId = stockDao.saveOrUpdate(newStock).getId();
Stock stock = stockDao.findById(stockId);
Item item = new Item();
item.setStock(stock);
stock.getItems().add(item);
Stock savedStock = stockDao.saveOrUpdate(stock);
Stock foundStock = stockDao.findById(savedStock.getId());
Set<Item> items = foundStock.getItems();
Item foundItem = items.iterator().next();
assertThat(foundItem.getId(), allOf(notNullValue(), greaterThan(0L))); // Assertion error here
assertTrue(items.contains(item));
assertNotNull(foundItem.getStock());
assertEquals(foundItem.getStock(), foundStock);
}
When I use stockDao.saveOrUpdate() method to save Stock to DB I got an assertion error that foundItem.getId() is null but it should be bigger than 0. But if I change saveOrUpdate to persist method I'll get an expected behaviour. Item will get a next id from a sequence and then save. But it happens only in tests. If I deploy my web app to a tomcat the cascade still will not work independently of called method. I read about these methods but didn't understand why they show such a different behavior. Help me guys to understand what I am doing? Why cascade operation is not working?