我已经创建了一个与您场景类似的情况(嵌入式数据库):
首先,我向数据库中添加任意内容,例如:
public void initialize() {
Sample startEntity = new Sample();
startEntity.setId(1);
startEntity.setName("Start name");
sampleRepository.saveSample(startEntity);
sampleRepository.flush();
sampleRepository.clear();
LOGGER.info(sampleRepository.findSampleById(1));
sampleRepository.clear();
}
在此之后,我们在数据库中得到了一个实体样本(所有事务都已完成并清除缓存);
控制台:
Hibernate: insert into sample (name, id) values (?, ?)
Hibernate: select sample0_.id as id1_0_0_, sample0_.name as name2_0_0_ from sample sample0_ where sample0_.id=?
2016-04-20 15:58:21.762 INFO 5764 --- [ main] com.patrykwoj.service.BasicServiceTest : Sample [id=1, name=Start name]
现在,您的示例:
@Transactional
@Component
public class SampleService {
private static final Logger LOGGER = Logger.getLogger(SampleService.class);
@Autowired
SampleRepository sampleRepository;
@Transactional (propagation = Propagation.REQUIRES_NEW)
public void method1() {
Sample someSample = new Sample();
someSample.setId(1);
someSample.setName("TestSample before update but after create");
sampleRepository.updateSample(someSample);
}
public void method2() {
method1();
Sample someSampleAfterUpdate = sampleRepository.findSampleById(1);
LOGGER.info(someSampleAfterUpdate);
}
}
然后从您的代码执行中控制台输出:
Hibernate: select sample0_.id as id1_0_0_, sample0_.name as name2_0_0_ from sample sample0_ where sample0_.id=?
2016-04-20 16:02:17.903 INFO 5044 --- [ main] com.patrykwoj.service.SampleService : Sample [id=1, name=TestSample before update but after create]
Hibernate: update sample set name=? where id=?
2016-04-20 16:02:17.903 INFO 5044 --- [ main] com.patrykwoj.StackOverfloApplication : Method2 is over
主类:
@Override
public void run(String... strings) throws Exception {
basicServiceTest.initialize();
sampleService.method2();
LOGGER.info("Method2 is over");
}
在我看来一切看起来都很好。它按照预期工作。我在你的代码上做了一些评论,但控制台输出应该很清晰。