下面的代碼工作, 但是,如果我刪除flush()和clear()調用, 然後第二次調用showTable()不顯示更新名稱「joan」,但「約翰」。JPA createQuery和清除/清除
什麼是正確的方式來實現這一點,而不調用flush()和clear()?
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.Customer;
@ContextConfiguration(locations = {"classpath:spring/test/spring-test.xml"})
@TransactionConfiguration(transactionManager = "txManager")
public class Test extends AbstractTransactionalJUnit4SpringContextTests {
private final Logger log = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void test() throws Exception {
Customer customer = new Customer();
customer.setName("john");
entityManager.persist(customer);
entityManager.flush();
entityManager.clear();
showTable();
final Query query = entityManager.createQuery("update Customer c set c.name='joan'");
int updateCount = query.executeUpdate();
log.debug("Update count: " + updateCount);
entityManager.flush();
entityManager.clear();
showTable();
}
public void showTable() {
final Query query = entityManager.createQuery("select c FROM Customer c");
List<Customer> list = query.getResultList();
for (Customer customer: list) {
log.info("customer name: " + customer.getName());
}
}
}
你需要_both_清空/清除呼叫,或只有一個特定的對? – jtahlborn
看看這個:http://stackoverflow.com/q/4415211/738746 –