記錄今天偶然發現的一個隱藏的bug
具體是這樣的:在一個事物中查詢出一條記錄例如Student id=1,然後修改student對象的一個屬性例如name,再通過jpa執行update 語句修改一個字段age 例如:update student set age = 1 where id=1。最後發現數據庫中除了age更新之外,name字段也做了更新,一條update 指令執行了兩次update。測試代碼如下
service
@Service
@Transactional(readOnly = true)
public class LabelConfigService {
private ISysLabelConfigRepository iSysLabelConfigRepository;
@Autowired
public LabelConfigService(ISysLabelConfigRepository iSysLabelConfigRepository){
this.iSysLabelConfigRepository = iSysLabelConfigRepository;
}
@Transactional
public void testUpdate() {
SysLabelConfig labelConfig = iSysLabelConfigRepository.findOne(2637);
labelConfig.setRemark("wlllllllllllll");
//即使不執行下面的update labelConfig依然會update
iSysLabelConfigRepository.updateSource(labelConfig.getId(),12);
}
}
repository
public interface ISysLabelConfigRepository extends JpaRepository<SysLabelConfig,Integer>
,JpaSpecificationExecutor<SysLabelConfig> {
@Modifying
@Query("update SysLabelConfig set source=?2 where id=?1")
void updateSource(Integer id, Integer source);
}
test
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationBootstrap.class)
@WebAppConfiguration
public class TestSysLabelConfig {
@Autowired
private LabelConfigService labelConfigService;
@Test
public void testUpdate(){
labelConfigService.testUpdate();
}
}
執行sql如下
0:24:16.495 [main] INFO c.c.j.m.s.s.TestSysLabelConfig - Started TestSysLabelConfig in 23.558 seconds (JVM running for 25.682)
Hibernate: select syslabelco0_.id as id1_17_0_, syslabelco0_.create_time as create_t2_17_0_, syslabelco0_.creator as creator3_17_0_, syslabelco0_.label_category as label_ca4_17_0_, syslabelco0_.label_name as label_na5_17_0_, syslabelco0_.label_sub_category as label_su6_17_0_, syslabelco0_.remark as remark7_17_0_, syslabelco0_.source as source8_17_0_ from sys_label_config syslabelco0_ where syslabelco0_.id=?
Hibernate: update sys_label_config set label_category=?, label_name=?, label_sub_category=?, remark=?, source=? where id=?
Hibernate: update sys_label_config set source=? where id=?
實際上即使不執行update語句,修改後的數據庫實體對象也會自動更新!!!
解決方法
1.在事物下不要修改實體對象的屬性
2.將事物放在repository的接口方法上
ps:在事物中對實體對象的操作要小心,最好不要修改實體對象的屬性或者將實體對象轉換爲vo對象再進行進一步的操作