I have written a test, which I know is wrong. I know that this gets the same instance for originalProduct and updatedProduct so that when I call updatedProduct.setProductName("Updated Product Name"); it updates the productName member of both originalProduct and updatedProduct. How can I change this so that I get 2 different instances of this object.
@Test
@Transactional
public void testUpdateProduct() {
productDao.addProduct(createTempProduct());
Product originalProduct = productDao.getProduct((long)999);
Product updatedProduct = productDao.getProduct((long)999);
updatedProduct.setProductName("Updated Product Name");
productDao.updateProduct(updatedProduct);
Product newProduct = productDao.getProduct((long)999);
Assert.assertNotSame(originalProduct, newProduct);
Assert.assertSame(updatedProduct, newProduct);
}
You’re hitting Hibernate’s first-level cache. In other words, every call to productDao.getProduct(999) within the scope of that test will return the same Product instance because the first time you load it, the instance is stored in the Session just in case you ask for it again. In order to avoid this, you can either evict the specific object from the Session or clear all objects from the Session between the calls.