[英]Spring data - entity not updated
I have an entity Customer
and Spring data interface CustomerRepository
shown below: 我有一个实体Customer
和Spring数据接口CustomerRepository
如下所示:
public interface CustomerRepository extends JpaRepository<Customer,Long> {
Customer findCustomerByName(String name);
}
I save Customer
object in the database and then update one field like this: 我将Customer
对象保存在数据库中,然后更新一个字段,如下所示:
customerRepository.save(new Customer("John", "Smith"));
Customer john = customerRepository.findCustomerByName("John");
john.setSurname("Barton");
customerRepository.flush();
customerRepository.findAll().forEach(System.out::println);
I don't understand why it prints: Customer(id=1, name=John, surname= Smith ). 我不明白为什么打印:Customer(id = 1,name = John,surname = Smith )。
As far as I know, Hibernate uses dirty checking
mechanism to update entities in persistent state. 据我所知,Hibernate使用dirty checking
机制来更新处于持久状态的实体。 So changed surname should be propagated to the database during end of transaction (but it does not - even if I separate this code into two @Transactional
methods). 因此,更改的姓氏应在事务处理结束时传播到数据库(但是,即使我将此代码分成两个@Transactional
方法,也不能这样做)。 Am I doing something wrong? 难道我做错了什么? Do I really need to save
object manually after each change? 每次更改后,我真的需要手动save
对象吗? Why surname field is not updated in the database? 为什么姓氏字段未在数据库中更新?
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepoTest {
@Autowired
private CustomerRepository customerRepository;
@Test
//NOTE: No @Transactional
public void testSaveFails() throws Exception {
customerRepository.save(new Customer("John", "Smith"));
Customer john = customerRepository.findCustomerByName("John");
john.setSurname("Barton");
customerRepository.flush();
customerRepository.findAll().forEach(System.out::println);
}
@Test
@Transactional
public void testSaveWorks() throws Exception {
customerRepository.save(new Customer("John", "Smith"));
Customer john = customerRepository.findCustomerByName("John");
john.setSurname("Barton");
//customerRepository.flush(); Flush is not necessary
customerRepository.findAll().forEach(System.out::println);
}
}
To explain: Hibernate keeps a cache of objects it loaded during a transaction. 解释一下:Hibernate保留了在事务期间加载的对象的缓存。 When a find method is executed, the id of a newly loaded object is compared to the id of the object in this cache, if found, the cached version is used. 当执行find方法时,会将新加载的对象的ID与该缓存中的对象的ID进行比较(如果找到),则使用缓存的版本。
@Transactional
works. 这就是使用@Transactional
的版本起作用的原因。 If you miss the @Transactional
(assuming auto-commit on the underlying transaction, which is most likely the case): 如果您错过了@Transactional
(假设自动提交基础事务,则很可能是这种情况):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.