How to get a separate instance from Hibernate in a Spring JUnit test
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.
Create a new Product
, and get all the values from the DB-product and set those values in the new object. Then its a dupe of the original object, at least in terms of values.
精彩评论